my Python Solution, shorter and simpler logic than top rated


  • 0
    C

    This code avoids duplicates and subsets that are greater than target.
    for example, [1,2] target 4
    I am only checking subsets against nums
    [] [1,2] range(0,2)

    [1] [1,2] range(0,2)
    [2] [2] range(0,1)

    [1,1] [1,2] range(0,2)
    [1,2] [2] range(0,1)

    [1,1,1] [1,2] range(0,2)
    [1,1,2] [2] range(0,1)

    and so on.

    class Solution(object):
        def combinationSum(self, nums, target):
            res = []
            self.helper(nums, res, [], target, 0)
            return res
        def helper(self, nums, res, sub, target, index):
            if sum(sub) == target:
            	res.append(sub)
        	for i in range(len(nums)):
        		if sum(sub + [nums[i]]) <= target:
        			self.helper(nums[i:], res, sub + [nums[i]],target, i)
    

Log in to reply
 

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