76ms Python recursive solution


  • 0
    J

    {

    class Solution():
        def combinationSum2(self, candidates, target):
                candidates.sort()
                ans = []
                l = len(candidates)
        
                def combinationSum(i, t, res):
                    if t == 0:
                        ans.append(list(res))
                        return
        
                    for j in xrange(i, l):
                        v = candidates[j]
                        # No duplicate in iteration. They have been handled during 
                        # recursion.
                        if j > i and v == candidates[j - 1]:
                            continue
        
                        # Fail fast
                        if t < v:
                            break
        
                        res.append(v)
                        combinationSum(j + 1, t - v, res)
                        res.pop()
                combinationSum(0, target, [])
                return ans
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.