标签:
backtracking,自己很快写出来了,很开心呢
1 public List<List<Integer>> combinationSum3(int k, int n) { 2 List<List<Integer>> res = new ArrayList<List<Integer>>(); 3 helper(res, new ArrayList<Integer>(), 1, k, n, 0); 4 return res; 5 } 6 7 private void helper(List<List<Integer>> res, List<Integer> item, int start, int k, int n, int curSum) { 8 if(item.size() == k) { 9 if(curSum == n) { 10 res.add(new ArrayList<Integer>(item)); 11 } 12 return; 13 } 14 for(int i = start; i <= 9; i++) { 15 if(curSum + i <= n) { 16 item.add(i); 17 helper(res, item, i + 1, k, n, curSum + i); 18 item.remove(item.size() - 1); 19 } 20 } 21 }
标签:
原文地址:http://www.cnblogs.com/warmland/p/5700030.html