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.
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>();
if(n <= 0 || k <= 0)
return res;
int[] nums = new int[9];
for(int i = 0; i < nums.length; i++)
nums[i] = i + 1;
List<Integer> line = new ArrayList<>();
helper(res, line, nums, 0, k, n);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> line, int[] nums, int start, int k, int n) {
if(line.size() == k) {
if(n == 0) {
res.add(new ArrayList<>(line));
}
return;
}
if(start == nums.length)
return;
for(int i = start; i < nums.length; i++) {
line.add(nums[i]);
helper(res, line, nums, i + 1, k, n - nums[i]);
line.remove(line.size() - 1);
}
}
}