Leetcode: Combination Sum II

Question

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 (a1, a2, … , 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]
Show Tags
Show Similar Problems

My first try

class Solution(object):
    def combinationSum2(self, candidates, target):
        """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """

        res = []
        if candidates==None or candidates==[]:
            return res

        candidates.sort()
        self.helper(candidates, 0, target, [], res)
        return res

    def helper(self, lst, start, target, item, res):
        if target<0:
            return 
        if target==0:
            res.append(item)
            return

        for ind in range(start,len(lst)):
            self.helper(lst, ind+1, target-lst[ind], item+[lst[ind]], res)

Error ouput:

Input:  [1,1], 1
Output: [[1],[1]]
Expected:  [[1]]

Solution

Get idea from here.

class Solution(object):
    def combinationSum2(self, candidates, target):
        """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """

        res = []
        if candidates==None or candidates==[]:
            return res

        candidates.sort()
        self.helper(candidates, 0, target, [], res)
        return res

    def helper(self, lst, start, target, item, res):
        if target<0:
            return 
        if target==0:
            res.append(item)
            return

        for ind in range(start,len(lst)):
            if ind>start and lst[ind]==lst[ind-1]:
                continue
            self.helper(lst, ind+1, target-lst[ind], item+[lst[ind]], res)

To avoid having the duplication, should add

 if ind>start and lst[ind]==lst[ind-1]:
                continue

你可能感兴趣的:(Leetcode: Combination Sum II)