[Leetcode] Combination Sum III
这里只能使用1到9九个数字,并且使用的数字的个数有限制。方法类似
1 public class Solution { 2 public void dp(List<List<Integer>> list, List<Integer> listone, int tmpsum, int start, int k, int target){ 3 if(tmpsum==target&&listone.size()==k){ 4 List<Integer> newlist = new LinkedList<Integer>(); 5 newlist.addAll(listone); 6 list.add(newlist); 7 return; 8 } 9 if(listone.size()==k) return; 10 //listone.add(start); 11 for(int s=start;s<=9;s++){ 12 listone.add(s); 13 dp(list,listone,tmpsum+s,s+1,k,target); 14 listone.remove(listone.size()-1); 15 } 16 //listone.remove(listone.size()-1); 17 return; 18 } 19 public List<List<Integer>> combinationSum3(int k, int n) { 20 List<List<Integer>> list = new LinkedList<List<Integer>>(); 21 List<Integer> listone = new LinkedList<Integer>(); 22 for(int i=1;i<=9;i++){ 23 listone.add(i); 24 dp(list,listone,i,i+1,k,n); 25 listone.remove(listone.size()-1); 26 } 27 return list; 28 } 29 }