zoukankan      html  css  js  c++  java
  • leetcode -- Combination Sum

    Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

    The same repeated number may be chosen from C unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • Elements in a combination (a1a2, � , ak) must be in non-descending order. (ie, a1 ? a2 ? � ? ak).
    • The solution set must not contain duplicate combinations.

    For example, given candidate set 2,3,6,7 and target 7
    A solution set is: 
    [7] 
    [2, 2, 3] 

     [易错点]

    1.递归终止条件不完整,当输入是:

    [2], 1 即可能递归会一直进行下去导致栈溢出

    2. line 29 的循环初始条件:
    开始的写法是i每次递归时都是从0开始,在输入是[1,2], 3, 产生输出:[[1,1,1],[1,2],[2,1]]
    正确的做法应该是从depth开始
     1 public class Solution {
     2     public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
     6         int len = candidates.length, depth = 0;
     7         if(len == 0){
     8             return result;
     9         }
    10         ArrayList<Integer> output = new ArrayList<Integer>();
    11         int sum = 0;
    12         Arrays.sort(candidates);
    13         generate(result, output, sum, depth, len, target, candidates);
    14         return result;
    15     }
    16     
    17     public void generate(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> output, int sum,
    18             int depth, int len, int target, int[] candidates){
    19             if(sum > target){
    20                 return;
    21             }
    22             if(sum == target){
    23                 ArrayList<Integer> tmp = new ArrayList<Integer>();
    24                 tmp.addAll(output);
    25                 result.add(tmp);
    26                 return;
    27             }
    28             
    29             for(int i = depth; i < len; i++){
    30                 sum += candidates[i];
    31                 output.add(candidates[i]);
    32                 generate(result, output, sum, i, len, target, candidates);
    33                 sum -= output.get(output.size() - 1);
    34                 output.remove(output.size() - 1);
    35             }
    36         }
    37 }
  • 相关阅读:
    [Linux] XShell 远程 Ubuntu 云主机,图形化界面打开Chrome
    [UI] 工具 & 框架
    你不知道的<input type="file">的小秘密
    vue3逻辑分离和页面快速展示数据
    vue中props参数的使用
    vue3.0中reactive的正确使用姿势
    CF986B Petr and Permutations(逆序对)
    洛谷P1972 [SDOI2009]HH的项链(莫队)44分做法
    2021牛客暑期多校训练营5 B. Boxes(概率期望)
    2021牛客暑期多校训练营5 K. King of Range(单调队列)详细题解
  • 原文地址:https://www.cnblogs.com/feiling/p/3266369.html
Copyright © 2011-2022 走看看