216. Combination Sum III

一、题目

  1、审题

  

  2、分析

    给出数值 k 代表可以使用 1~9 中的 k 个不同数字,n 代表这 k 个数字的和。求所有符合的组合。

 

二、解答

  1、思路:

    采用 DFS

 1     public List<List<Integer>> combinationSum3(int k, int n) {
 2         
 3         List<List<Integer>> resultList = new ArrayList<>();
 4         DFShelper(resultList, new ArrayList<Integer>(), k, n, 1);
 5         return resultList;
 6     }
 7     
 8     private void DFShelper(List<List<Integer>> resultList,
 9             ArrayList<Integer> targetList, int k, int sum, int i) {
10         
11         if(sum < 0)
12             return;
13         if(k == 0) {
14             if(sum == 0)
15                 resultList.add(new ArrayList<>(targetList));
16             return;
17         }
18         
19         for (int j = i; j <= 9; j++) {
20             targetList.add(j);
21             DFShelper(resultList, targetList, k - 1, sum - j, j + 1);
22             targetList.remove(targetList.size() - 1);
23             
24             if(sum - (j + 1) < 0)
25                 return;
26         }
27     }

 

posted @ 2018-11-02 11:19  skillking2  阅读(140)  评论(0编辑  收藏  举报