Skip to content
LC-0039 Medium LeetCode

39. Combination Sum

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 74% Topics: Array, Backtracking
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(k * n^k)
# Space: O(k)

class Solution(object):
    # @param candidates, a list of integers
    # @param target, integer
    # @return a list of lists of integers
    def combinationSum(self, candidates, target):
        result = []
        self.combinationSumRecu(sorted(candidates), result, 0, [], target)
        return result

    def combinationSumRecu(self, candidates, result, start, intermediate, target):
        if target == 0:
            result.append(list(intermediate))
        while start < len(candidates) and candidates[start] <= target:
            intermediate.append(candidates[start])
            self.combinationSumRecu(candidates, result, start, intermediate, target - candidates[start])
            intermediate.pop()
            start += 1

Solution from kamyu104/LeetCode-Solutions · MIT