LeetCode 40. Combination Sum II

来源:互联网 发布:黑金手游充值软件 编辑:程序博客网 时间:2024/05/13 06:15

题目:

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

Each number in C 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.

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
A solution set is: 

[  [1, 7],  [1, 2, 5],  [2, 6],  [1, 1, 6]]
题意:
如39题一样,只是不能有重复的组合。

题解:

加一个去重判断

class Solution(object):    def combinationSum2(self, candidates, target):        """        :type candidates: List[int]        :type target: int        :rtype: List[List[int]]        """        res = []          candidates.sort()        self.dfs(candidates, target, 0, [], res)        r = []        for item in res:            if item not in r:                r.append(item)        return r    def dfs(self, nums, target, index, path, res):           if target < 0: #小于0时,回溯              return          if target == 0:              res.append(path)              return           for i in range(index, len(nums)):             self.dfs(nums, target-nums[i], i+1, path+[nums[i]], res) 


0 0
原创粉丝点击