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()

你可能感兴趣的:(算法,leetcode,python,数据结构)