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]]
本题在combination2的基础上,添加了元素个数,比较简单,代码如下:
1 public class Solution { 2 public List<List<Integer>> combinationSum3(int k, int n) { 3 List<List<Integer>> res = new ArrayList<>(); 4 int[] num = new int[]{1,2,3,4,5,6,7,8,9}; 5 backtracking(res,new ArrayList<Integer>(),num,k,n,0); 6 return res; 7 } 8 public void backtracking(List<List<Integer>> res,List<Integer> list,int[] num,int k,int target,int start){ 9 if(list.size()>k) return; 10 if(target<0) return; 11 else if(target==0){ 12 if(list.size()==k) 13 res.add(new ArrayList<Integer>(list)); 14 }else{ 15 for(int i=start;i<num.length;i++){ 16 list.add(num[i]); 17 backtracking(res,list,num,k,target-num[i],i+1); 18 list.remove(list.size()-1); 19 } 20 } 21 } 22 }