zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    1021 个位数统计
    1020 月饼
    1019 数字黑洞
    1018 锤子剪刀布
    1017 A除以B
    1016 部分A+B
    1015 德才论
    1014 福尔摩斯的约会
    cocos2d 间隔动作
    cocos2d 瞬时动作
  • 原文地址:https://www.cnblogs.com/skillking/p/9895223.html
Copyright © 2011-2022 走看看