LeetCode 40. 组合总和 II

40. 组合总和 II

Difficulty: 中等

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]

Solution

这道题跟39题类似,只不过给定数组中的数只能使用一次(下一次递归的时候从i+1的下标开始),并且解的集合中不能有重复的,比如candidates = [2,5,2,1,2]target = 5,解的集合中就只能有[1,2,5][2,1,5][5,1,2]之中的一种。为了避免这种情况,首先需要对数组排序,然后再递归的时候判断此时节点上的数与上一个数是否相同,如果是则跳过。

回顾39题中提到的框架:

result = []
def backtrack(路径, 选择列表):
    if 满足结束条件:
        result.add(路径)
        return

    for 选择 in 选择列表:
        做选择
        backtrack(路径, 选择列表)
        撤销选择

回答两个问题:1. 递归什么时候结束?2. 元素是可以被重复使用的还是不可以被重复使用的?

  1. 数组内元素每次被使用之后,target减去该元素,直到target被减到0,说明找到了满足和为target的组合。
  2. 元素不能被重复使用,所以下一次递归的选择列表不包括此时的元素(下标从i+1开始)

解法一:

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        if sum(candidates) < target:
            return []
        #先把candidates排序一下
        candidates.sort()            
        path = []
        res = []
        self.backtrack(candidates, path, target, res, 0)
        return res
        
    def backtrack(self, nums, path, target, res, start):
        if target < 0:
            return
        if target == 0:
            res.append(path[:])
            return
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i-1]:
                continue
            path.append(nums[i])
            self.backtrack(nums, path, target - nums[i], res, i + 1)
            path.pop()

解法二:

class Solution:
   def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
       if not candidates or not target:
           return []
       res = []
       candidates.sort()
       self.dfs(candidates, target, [], res)
       return res
       
   def dfs(self, nums, target, path, res):
       if target < 0:
           return
       if target == 0:
           res.append(path)
           return
       for i in range(len(nums)):
           if i-1 >= 0 and nums[i] == nums[i-1]:
               continue
           self.dfs(nums[i+1:], target-nums[i], path + [nums[i]], res)

相关题目:

  1. LeetCode 39. 组合总和 - swordspoet - 博客园
  2. LeetCode 17. 电话号码的字母组合 - swordspoet - 博客园
posted @ 2021-03-26 15:48  swordspoet  阅读(42)  评论(0编辑  收藏  举报