216. Combination Sum III

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     }

 

posted @ 2016-07-24 06:56  warmland  阅读(124)  评论(0编辑  收藏  举报