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]]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
public class Solution { public List<List<Integer>> combinationSum3(int k, int n) { int nums[] = {1,2,3,4,5,6,7,8,9}; List<List<Integer>> res = new ArrayList<>(); List<Integer> member = new ArrayList<>(); dfs(res, member, 0, nums, n, k); return res; } public void dfs(List<List<Integer>> res, List<Integer> member, int deep, int[] nums, int n, int k){ if(member.size() > k || n < 0) return; if(member.size() == k && n == 0) { res.add(new ArrayList<>(member)); return; } for(int i = deep ; i < nums.length; i++){ member.add(nums[i]); dfs(res, member, i+1, nums, n-nums[i], k); member.remove(member.size()-1); } } }