# 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.

**Note:**

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

**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]]
```

## Solution

Basically the same idea as Combination I, II. The difference is that the given candidates is now 1, 2, ..., 9 for each position in the combination, and the constraints is the number of numbers in the combination. So there's similarities with Combinations too.

```java
class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ans = new ArrayList<>();

        comboHelper(1, n, k, new ArrayList<Integer>(), ans);

        return ans;
    }

    private void comboHelper(int start, int remain, int k, List<Integer> combo, List<List<Integer>> ans) {
        if (remain == 0) {
            if (combo.size() == k) {
                ans.add(new ArrayList<Integer>(combo));
            }
            return;
        }

        for (int i = start; i <= 9; i++) {
            combo.add(i);
            comboHelper(i + 1, remain - i, k, combo, ans);
            combo.remove(combo.size() - 1);
        }
    }
}
```

## Reference

<https://leetcode.com/problems/combination-sum-ii/discuss/16878/Combination-Sum-I-II-and-III-Java-solution-(see-the-similarities-yourself\\>)


---

# Agent Instructions: 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://aaronice.gitbook.io/lintcode/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.
