Combination Sum III(Medium)
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.
Ensure that numbers within the set are sorted in ascending order.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
解题思路:回溯+DFS
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (n <= 0 || k <= 0) {
return res;
}
if (k > 9 || n > 55 )
return res;
List<Integer> cur = new ArrayList<Integer>();
helper(cur, res, 1, n, k);
return res;
}
public void helper(List<Integer> current, List<List<Integer>> res, int index, int target, int k) {
if (current.size() == k && target == 0) {
res.add(new ArrayList<Integer>(current));
return;
}
if (current.size() > k || target < 0) {
return;
}
for (int i = index; i <= 9; i++) {
current.add(i);
helper(current, res, i + 1, target - i, k);
current.remove(current.size() - 1);
}
}