Leetcode40.组合总和II - Combination Sum - Python - 回溯法

解题思路:

1.理解数层去重和树枝去重。本题只需要数层去重。数层去重需要这样做:

if i > startIndex and candidates[i] == candidates[i-1] and not used[i-1]:
                continue

used[i-1]不写也没事。

树枝去重是通过每次递归时的i+1来实现的。

2.需要先将candidates排序,以进行candidates[i]和candidates[i-1]的比较。

3.剪枝操作。

代码:

class Solution(object):
    result = []
    path = []
    def combinationSum2(self, candidates, target):
        self.result = []
        candidates.sort()
        used = [False] * len(candidates)
        self.traceBack(candidates, target, 0, 0, used)
        return self.result

    def traceBack(self, candidates, target, total, startIndex, used):
        if total == target:
            self.result.append(self.path[:])
            return

        for i in range(startIndex, len(candidates)):
            if i > startIndex and candidates[i] == candidates[i-1] and not used[i-1]:
                continue
            if total > target:
                break
            total += candidates[i]
            used[i] = True
            self.path.append(candidates[i])
            self.traceBack(candidates, target, total, i+1, used)
            used[i] = False
            total -= candidates[i]
            self.path.pop()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值