Easy Python Code Beats 98%


  • 0
    class Solution(object):
        def __init__(self):
            self.ans = []
    
        def recursive(self, candidates, target, start, trace):
            if(start < len(candidates) and candidates[start] <= target):
                if target - candidates[start] > 0:      # the first branch
                    self.recursive(candidates, target - candidates[start],
                                   start, trace + [candidates[start]])
                elif target - candidates[start] == 0:
                    self.ans.append(trace + [candidates[start]])
                self.recursive(candidates, target, start + 1, trace)    # the second branch
    
        def combinationSum(self, candidates, target):
            candidates = sorted(candidates)
            self.recursive(candidates, target, 0, [])
            return self.ans
    

Log in to reply
 

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