Share my Python answer and does it work?


  • 0
    N
    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        return self.answer(candidates, target)
    def answer(self, candidates, target):
        ans = []
        if target < candidates[0]:
            return []
        if len(candidates) == 1 and target / candidates[0] * candidates[0] == target:
            return [[candidates[0]] * (target / candidates[0])]
        for i in range(0,len(candidates)):
            if candidates[i] < target:
                s = self.answer(candidates[i:], target - candidates[i])
                if s == []:
                    continue
                else:
                    for x in s:
                        ans.append([candidates[i]] + x)
            elif candidates[i] == target:
                 ans.append([candidates[i]])
            else:
                break
        return ans

Log in to reply
 

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