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.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList<>();
sum(result, new ArrayList<Integer>(), n, k, 1);
return result;
}

public void sum(List<List<Integer>> result, ArrayList<Integer> cur, int target, int k, int num) {
if (target == 0 && cur.size() == k) {
result.add(new ArrayList<Integer>(cur));
} else if (target > 0 && cur.size() < k) {
for (int start = num; start < 10; start++) {
cur.add(start);
sum(result, cur, target - start, k, start + 1);
cur.remove(cur.size() - 1);
}
}
}
}