📉
leetcode-题解
  • leetcode-notes
  • linked-list
    • 2-Add-Two-Numbers
    • 109-Convert-Sorted-List-to-Binary-Search-Tree
    • 19-Remove-Nth-Node-From-End-of-List
    • 92-Reverse-Linked-List-II
    • 142-Linked-List-Cycle-II
    • 83-Remove-Duplicates-from-Sorted-List
    • 61-Rotate-List
    • 148-Sort-List
    • 86-Partition-List
    • 82-Remove-Duplicates-from-Sorted-List-II
    • 138-Copy-List-with-Random-Pointer
    • 328-Odd-Even-Linked-List
    • 23- Merge-k-Sorted-Lists
    • 25-Reverse-Nodes-in-k-Group
  • templates
    • bitmap
    • ologn
    • Morris
    • dp
    • binary-search
    • Maxwindow
    • 递归
    • union
    • graph
    • greedy-algorithm
    • kmp
    • list
    • ordered-list
    • tree
    • Manacher
    • Monotonic-stack
    • big-data
    • sort-Summary
    • Bucket-sort
    • bit-opreation
    • heap-sort
  • arrays
    • others
      • 31-Next-Permutation
      • 66-Plus- One
      • 229-Majority-Element-II
      • 414-Third-Maximum-Number
    • matrix
      • 74-Search-a-2D-Matrix
      • 289-Game-of-Life
    • PrefixOrSuffix
      • 560-Subarray-Sum-Equals-K
      • 238-Product-of-Array-Except-Self
    • 二分法
      • rotated-array-problem
      • D天内送达包裹的能力
      • 162-Find-Peak-Element
      • Minimize-maximum-and-maximize-minimum
    • 多指针
      • 611-Valid-Triangle-Number
      • 228-Summary-Ranges
      • 75-Sort-Colors
      • 18-4Sum
      • 27-Remove-Element
      • 三数之和
      • 26-Remove-Duplicates-from-Sorted-Array
      • 盛最多水的容器
      • 80-Remove-Duplicates-from-Sorted-Array-II
      • 最接近的三数之和
    • array-circle
      • 457-Circular-Array-Loop
      • 287-Find-the-Duplicate-Number
      • 565-Array-Nesting
    • 智力题
      • 73-Set-Matrix-Zeroes
      • 最佳观光组合
    • 几何问题
      • 统计全为1的正方形子矩阵
      • 495-Teemo-Attacking
    • sort
      • 88-Merge-Sorted-Array
      • 57-Insert-Interval
  • tree
    • 105-Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal
    • 230-Kth-Smallest-Element in-a-BST
    • 106-Construct-Binary-Tree-from-Inorder-and-Postorder-Traversal
    • 257-Binary-Tree-Paths
    • 113-Path-Sum-II
    • 96-Unique-Binary-Search-Trees
    • 124-Binary-Tree-Maximum-Path-Sum
    • 103-Binary-Tree-Zigzag-Level-Order-Traversal
    • 426-Convert-Binary-Search-Tree-to-Sorted-Doubly-Linked-List
    • 117-Populating-Next-Right-Pointers-in-Each-Node-II
    • 99-Recover-Binary-Search-Tree
    • 366-Find-Leaves-of-Binary-Tree
    • 337-House-Robber-III
    • 333-Largest-BST-Subtree
    • 298-Binary-Tree-Longest-Consecutive-Sequence
    • 428-Serialize-and-Deserialize-N-ary-Tree
    • 1367-Linked-List-in-Binary-Tree
    • 173-Binary-Search-Tree-Iterator
    • 98-Validate-Binary-Search-Tree
    • 156-Binary-Tree-Upside-Down
    • 404-Sum-of-Lef- Leaves
    • 255-Verify-Preorder-Sequence-in-Binary-Search-Tree
    • 272-Closest-Binary-Search-Tree-Value-II
    • 95-Unique-Binary-Search-Trees-II
    • 222-Count-Complete-Tree-Nodes
    • 431-Encode-N-ary-Tree to-Binary-Tree
    • Lowest-Common-Ancestor-of-a-Binary-Tree
    • 129-Sum-Root-to-Leaf-Numbers
  • recursive
    • 前言
    • 39-Combination-Sum
    • 79-Word-Search
    • 04-Power-Set-LCCI
    • 前言
    • 90-Subsets-II
    • 40-Combination-Sum-II
    • 351-Android-Unlock-Patterns
  • dynamic-programming
    • 276-Paint-Fence
    • 132-Palindrome-Partitioning-II
    • 361-Bomb-Enemy
    • 62-Unique-Paths
    • 376-Wiggle-Subsequence
    • 403-Frog-Jump
    • 32-Longest-Valid-Parentheses
    • 97-Interleaving-String
    • 354-Russian-Doll-Envelopes
    • 279-Perfect-Squares
    • 304-Range-Sum-Query-2D-Immutable
    • 10-Regular-Expression-Matching
    • Paint-House-series
    • 139-Word-Break
    • Best-Time-to-Buy-and-Sell-Stock-series
    • 416-Partition-Equal-Subset-Sum
    • 300-Longest-Increasing-Subsequence
    • 91-Decode-Ways
    • Ugly-Number-series
    • 363-Max-Sum-of-Rectangle-No-Larger-Than-K
    • 368-Largest-Divisible-Subset
    • 63-Unique-Paths-II
    • 312-Burst-Balloons
    • 322-Coin-Change
    • 64-Minimum-Path-Sum
    • 140-Word-Break-II
    • 120-Triangle
    • 72-Edit-Distance
    • House-Robber-series
    • 413-Arithmetic-Slices
    • 174-Dungeon-Game
    • 87-Scramble-String
    • 44-Wildcard-Matching
    • 338-Counting-Bits
    • 152-Maximum-Product-Subarray
    • 375-Guess-Number-Higher-or-Lower-II
  • hash-table
    • 381-Insert-Delete-GetRandom-O(1) - Duplicates-allowed
    • 442-Find-All-Duplicates-in-an-Array
    • 380-Insert-Delete-GetRandom-O(1)
    • 1-Two-Sum
    • 3-Longest-Substring-Without-Repeating-Characters
    • 41-First-Missing-Positive
  • stack
    • Monotonic stack
      • 84-Larges-Rectangle-in-Histogram
      • 42-Trapping-Rain-Water
  • bit-manipulation
    • 08-Draw-Line-LCCI
  • Mysql
    • 185-Department-Top-Three-Salaries
    • 177-N-Highest-Salary
    • 178-Rank-Scores
    • 180-Consecutive-Numbers
  • greedy
    • 56-Merge-Intervals
    • 55-Jump-Game
    • 53-Maximum-Subarray
  • math
    • 357-Count-Numbers-with-Unique-Digits
    • 343-Integer-Break
    • 119-Pascal's-Triangle-II
  • string
    • Palindrome
      • 5-Longest-Palindromic-Substring
      • Manacher
  • sliding-window
    • 209-Minimum-Size-Subarray-Sum
Powered by GitBook
On this page
  • 0x1 题目详情
  • 0x2 解题思路
  • 0x3 代码实现
  • 0x4 课后总结

Was this helpful?

  1. recursive

39-Combination-Sum

Previous前言Next79-Word-Search

Last updated 4 years ago

Was this helpful?

0x1 题目详情

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。

测试用例:

示例 1: 输入: candidates = [2,3,6,7], target = 7, 所求解集为: [ [7], [2,2,3] ]

0x2 解题思路

这道题的难点在于如何去重。初次看到这道题我就想不是和这道题差不多嘛。只不过是一个数能够选择一次或多次。说干就干。

对于一个数,我们有三种处理方式:

  • 放弃当前数

  • 使用当前数,但是只使用一次

  • 使用当前数,下一轮仍可使用该数

    结果发现有了大量的重复解,这个去重问题困扰了我很久,最后在答题区获得了答案。这种解法类似于深度优先遍历,我们将数组的每一个元素都作为路径的起点去处理,

具体的思路在图上也已经标明了,在这里仍要声明一下:排序是为了更快的找到答案,设置下一次搜索的起点才是去重的根本原因。至于为什么要选择设置下一次的搜索起点呢,这个通过画具体的路径图是可以得出来得。

0x3 代码实现

  1. 第一次实现得错误代码,这种思路对于那种每个元素只需要一次或零次的,且没有重复元素的好使一点。对于有重复元素的,会出现重复的结果。

class Solution {
  public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> result=new ArrayList<>();
    if(candidates==null || candidates.length==0){
        return result;
    }
    Arrays.sort(candidates);
    recur(target,candidates,0,result,new ArrayList<Integer>());
    return result;
  }
  private void recur(int target,int[] candidates,int index,List<List<Integer>> result,List<Integer> curResult){
    if(target==0){
        result.add(curResult);
        return;
    }

    if(target<0 || index>=candidates.length){
      return 0;
    }
    //对于一个元素我们有三种选中
    List<Integer> temp=new ArrayList<>(curResult);
    List<Integer> temp=new ArrayList<>(curResult);
    //不要当前元素
    recur(target,candidates,index+1,result,curResult);
    //只要当前元素一次
    recur(target-candidates[index],candidates,index+1,result,curResult);
    //要当前元素多次
    recur(target-candidates[index],candidates,index,result,curResult);
  }
}
  1. 下面是能够正确去重得代码,采用深度优先遍历的思想,虽然也是从头到尾找到目标路径,但不是像上面这种考虑每个元素要还是不要。而是考虑将每个元素都作为路径上的值,遍历所有的尝试,最后再根据题目特点去重、剪枝等等。

class Solution {
  public List<List<Integer>> combinationSum(int[] candidates, int target) {
      List<List<Integer>> result=new ArrayList<>();
      if(candidates==null || candidates.length==0){
          return result;
      }
      Arrays.sort(candidates);
      recur(target,candidates,0,result,new ArrayList<Integer>());
      return result;

  }
  private void recur(int target,int[] candidates,int index,List<List<Integer>> result,List<Integer> curResult){
      if(target==0){
          result.add(new ArrayList<Integer>(curResult));
          return;
      }
      //如果当前target已经小于最小的可用元素了,就不用再往下看了

      for(int i=index;i<candidates.length;i++){
          if(target<0||target<candidates[index]){
              return;
          }
          curResult.add(candidates[i]);
          recur(target-candidates[i],candidates,i,result,curResult);
          curResult.remove(curResult.size()-1);
      }
  }
}

0x4 课后总结

对于找路径的问题,尤其是递归的问题,怎么说呢,我总结了两种常用的尝试方法:

  • 第一种就是像该开始我思考的方向,从头到尾遍历元素,考虑的是我们要还是不要当前元素,要的话要多少,最后探测出base case即可。感觉这种对于没有重复的元素并且一个元素只有0或1这种选择时,比较好用。

  • 第二种就是我们不再思考哪个元素要,哪个元素不要。而是非常暴力对每个元素都作为路径上的一种尝试,遍历所有的结果。最后再根据路径时剪枝、去重等等。

而且而且,我怎么感觉这道题跟全排序挺像的,只是结果集中元素的个数没有要去。全排列也是找路径,只不过得用上所有的元素。

原题链接
求幂集
搜索路径图