[Leetcode]Combination Sum II

来源:互联网 发布:淘宝卖大米要什么手续 编辑:程序博客网 时间:2024/05/19 02:20

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.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 

Combination Sum 的扩展题~这题中单个元素不能重复使用~解法也是差不多的,注意递归的时候传进去的start应该是当前元素的下一个,还有注意判断重复元素时用的是i > start,Combination Sum里用的是i > 0,因为虽然一个元素不可以重复使用,但是如果这个元素重复出现是允许的,但是为了避免出现重复的结果集,我们只对于第一次得到这个数进行递归,接下来就跳过这个元素了,因为接下来的情况会在上一层的递归函数被考虑到,这样就可以避免重复元素的出现(参考自

http://blog.csdn.net/linhuanmars/article/details/20829099)

class Solution:    # @param candidates, a list of integers    # @param target, integer    # @return a list of lists of integers    def combinationSum2(self, candidates, target):        if candidates is None or len(candidates) == 0: return []        self.res = []        candidates.sort()        self.helper(candidates, target, 0, [])        return self.res            def helper(self, candidates, remainder, start, item):        if remainder == 0:            self.res.append(item[:])            return        if remainder < 0: return        for i in xrange(start, len(candidates)):            if i > start and candidates[i] == candidates[i - 1]:                continue            item.append(candidates[i])            self.helper(candidates, remainder - candidates[i], i + 1, item)            item.pop()


0 0
原创粉丝点击