> For the complete documentation index, see [llms.txt](https://luj.gitbook.io/code/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://luj.gitbook.io/code/dfs/backtracking/combination-sum-iii.md).

# Combination Sum III

Find all possible combinations of **k** numbers that add up to a number **n**, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

* All numbers will be positive integers
* The solution set must not contain duplicate combinations.

## Example

**Example 1:**

```
Input: k = 3, n = 7

Output:
 [[1,2,4]]
```

**Example 2:**

```
Input:
k = 3, n = 9

Output:
 [[1,2,6], [1,3,5], [2,3,4]]
```

## Note

组合从n个数中选k个数，n只能是\[1, 9]闭区间的值，起始start为1，DFS循环遍历

当k和n都为0的时候，递归退出

注意剪枝：n小于0的情况或者在循环中n小于i

## Code

```java
class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> res = new ArrayList<>();
        helper(res, new ArrayList<>(), k, n, 1);
        return res;
    }

    private static void helper(List<List<Integer>> res, 
                               List<Integer> list, int k, 
                               int n, int start) {
        if (k == 0 && n == 0) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = start; i <= 9; i++) {
            if (n < i) break;
            list.add(i);
            helper(res, list, k - 1, n - i, i + 1);
            list.remove(list.size() - 1);
        }
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://luj.gitbook.io/code/dfs/backtracking/combination-sum-iii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
