leetcode 每日一题 40. 组合总和 II

回溯法

思路:

参考39.组合总和,在回溯时加判断条件和改变开始位置达到去重。

代码:

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        candidates.sort()
        res = []
        path = []
        self.process(candidates,0,len(candidates),path,res,target)
        return res

    def process(self,candidates,begin,size,path,res,target):
        if target == 0:
            return res.append(path[:])
        if target < 0:
            return    
        for i in range(begin,size):
            if candidates[i]<=target and (i==begin or candidates[i] != candidates[i-1]):
                path.append(candidates[i])
                self.process(candidates,i+1,size,path,res,target-candidates[i])
                path.pop()

 

posted @ 2020-05-22 13:10  nil_f  阅读(97)  评论(0编辑  收藏  举报