Simple Python Solution With Brief Explanation


  • 0
    J

    Take the ith number as the first element, then the original problem can be turned into find the solution for the new target: target - candidates[i] in candidate[i:]. Recursively doing this until the target is smaller or equal than 0.

    class Solution(object):
        def combinationSum(self, candidates, target):
            """
            :type candidates: List[int]
            :type target: int
            :rtype: List[List[int]]
            """
            if target > 0:
                return [[candidates[i]]+s for i in range(len(candidates)) for s in self.combinationSum(candidates[i:], target-candidates[i])]
            elif target < 0:
                return []
            else:
                return [[]]

Log in to reply
 

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