【LeetCode】40. 组合总和 II

题目描述(中等难度)

【LeetCode】40. 组合总和 II_第1张图片
【LeetCode】40. 组合总和 II_第2张图片

解题思路

  1. 想将数组进行排序
  2. 然后再进行回溯
  3. 题目要求解集不能包含重复的组合,所以要加start

python 代码

class Solution:
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        trace = []
        res = []
        visit = [0]*len(candidates)
        candidates.sort()
        self.backtrace(candidates,0,target,trace,res,visit)
        return res
    
    def backtrace(self,candidates,start,target,trace,res,visit):
        if target == 0:
            res.append(trace[:])
            return
        
        for i in range(start,len(candidates)):
            if i >start and candidates[i]==candidates[i-1]:
                continue
            if visit[i] == 1:
                continue
            if target-candidates[i] < 0:
               return 0
            else:
                visit[i] = 1
                trace.append(candidates[i])
                self.backtrace(candidates,i+1,target-candidates[i],trace,res,visit)
                trace.pop()
                visit[i] = 0

s = Solution()
result = s.combinationSum2([10,1,2,7,6,1,5], 8)
print(result)  # 

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