leetcode_组合总和2_2种解法

题目

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

Each number in candidates may only be used once in the combination.

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

题目分析

  • 如何利用递归列举出合适的组合?

解法1

class Solution2:
    def combinationSum2(self, candidates, target):
        """
        代码缺陷:在当前层无法和targ 比较大小
        :param candidates:
        :param target:
        :return:
        """
        def recursion(candis, targ):

            if targ == 0:
                return [[]]  # 递归出口
            if len(candis) == 0 or targ < 0:
                return []   # 递归非正常出口
            return [[candis[0]] + x for x in \
                    recursion(candis[1:], targ - candis[0])] + \
                   recursion([c for c in candis if c > candis[0]], targ)

        return recursion(sorted(candidates), target)

解法1_Q&A

  • 代码1需要优化的地方:例如当前temp已经是[1,1,2,5],可是代码仍然继续比较剩下的数,构建出类似于[1,1,2,6] 的组合,这边明明可以通过剪枝缩小进层数 NOTACK
  • recursion([c for c in candis if c > candis[0]], targ) 有何用
    答:用来筛选不合适的数,例如当前temp已经是[1,1,2,5],可是代码仍然继续比较剩下的数,构建出类似于[1,1,2,6] 的组合,此时candis[0]=5
  • return [] 和return [[]]的区别
for i in []:
    print('a',i)  # print nothing
    
for i in [[]]:
    print('a',i)
    
a []

解法2

class Solution:
    def combinationSum2(self, candidates, target):
        """
        :param candidates:
        :param target:
        :return:
        """
        n = len(candidates)
        candidates.sort()
        res = []

        def dfs(i, tmp_sum, tmp):
            if tmp_sum > target:
                return  # 返回上一层
            if tmp_sum == target:
                res.append(tmp)
                return  # 返回上一层
            for j in range(i, n):
                if tmp_sum + candidates[j] > target: break  # 解法1 需要优化的地方,因为整体是有序的,如果此时大于target,那么接下来的candidates 都不用比较
                if j > i and candidates[j] == candidates[j - 1]: continue  # 两个条件共同作用下,去掉重复比较 同一位置

                dfs(j + 1, tmp_sum + candidates[j], tmp + [candidates[j]])

        dfs(0, 0, [])

        return res


candidates = [10, 1, 2, 7, 6, 1, 5]
target = 8
result = Solution2().combinationSum2(candidates, target)
print(result)

解法2_Q&A

  • 为啥for 循环中要再弄一个判断是否大于target, 一个用来判断每次进层的tmp_sum 是否大于target,另一个是用来判断加上candidate[x] 后是否大于target
    答:其实可以合并成一个,但有两个判断使算法更高效,不用等到进层后才判断当前候选数是否合适

  • 当递归退层到合适的位置,是否还会继续前进
    答:例如检测组合[1,1,2,5]不成立,那么递归退层到[1,1] 那么此时应当是继续前进到5,也就是构成[1,1,5]<得益于i 无论如何都会运行下去,该条件满足>

  • 因为每个数字只能在组合中使用一次,so 如何避免同一个数字被多次使用
    答:if j > i and candidates[j] == candidates[j - 1] 刚开始i=0,j=0时,该语句不执行,当j>2时,因为列表已经是有序的,so 只需要比较第i个数和第i-1个数的大小(可能会产生重复解,例如[1,1,2,3],target 为4 会产生[[1,3],[1,1,2],[1,3]] 三种解 )即可<专业术语就是:相同递归深度的list 不会重复添加同一个数> NOTACK

Shoulders of Giants

题目来源于leetcode,解法来源于其下的评论区

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值