0:00 / 0:00

Find every combination that adds up to the target, reusing numbers as often as you like. Recurse with a start index so each combination appears once.

▼

The problem

LeetCode 39 (Medium). Given distinct positive numbers candidates and a target, return every unique combination of candidates that adds up to the target. A number may be used any number of times; combinations are unique as multisets ([2,2,3] and [2,3,2] are the same one).

Example: candidates [2, 3, 6, 7], target 7 → [[2,2,3], [7]].

def combination_sum(nums, target):
    nums.sort()
    out = []
    def go(start, remain, picks):
        if remain == 0:
            out.append(picks[:])  # a copy
            return
        for i in range(start, len(nums)):
            if nums[i] > remain:
                break             # too big
            picks.append(nums[i])
            go(i, remain - nums[i], picks)
            picks.pop()           # backtrack
    go(0, target, [])
    return out
TRY IT ON LEETCODE ▶

The solution

def combination_sum(nums, target):
    nums.sort()
    out = []
    def go(start, remain, picks):
        if remain == 0:
            out.append(picks[:])  # a copy
            return
        for i in range(start, len(nums)):
            if nums[i] > remain:
                break             # too big
            picks.append(nums[i])
            go(i, remain - nums[i], picks)
            picks.pop()           # backtrack
    go(0, target, [])
    return out

Transcript

Combination Sum. You get distinct positive numbers and a target. Return every combination that adds up to the target, and you may use each number as many times as you like.

Take two, three, six and seven, with a target of seven. Picture a cauldron that must fill exactly to seven, and each number is a potion you can pour again and again. Two, two and three works. So does seven alone.

The naive way pours in every order. It finds two, two, three, but also two, three, two, and three, two, two. That's one recipe three times over, so the answers repeat.

The fix is to choose in order. Sort the vials and keep a start index. After you pour a vial, you may pour it again, or any vial to its right, but never one to its left. Now each recipe is built just one way. And since the vials are sorted, the first one that overflows ends the loop: every vial after it is bigger.

In code, a helper takes the start index, the amount remaining, and the picks. When nothing remains, save a copy. Otherwise, loop from the start. If the number is too big, break. Else add it, recurse with the same index so it can repeat, and pop it back off. That pop is the backtrack.

Let's brew. Two, two, two leaves one. Nothing fits, so back up. Two, two, three hits seven exactly: save it. Two, three leaves two, but we can't go back to two. Three, three leaves one: a dead end. Six leaves one: another dead end. Last, seven alone: save it. Ten calls, two recipes, no repeats.

Every pour can branch again, so the time is exponential: roughly n to the power of the target over the smallest number. The space is the depth of the pours: at most the target over the smallest number, here three deep.

Pour in order, reuse freely, stop at the brim. That's Combination Sum.