← Whiteboard questions

Combination Sum

Find every way to reach a target by reusing numbers

DSA, Medium, Backtracking

Which structure or algorithm, and what does it cost.

A list candidates holds distinct positive whole numbers. Return every combination of them that adds up to target. You may use the same number as many times as you like. Two combinations are the same if every number is used the same number of times. Write each combination in increasing order. List the combinations in any order. If there is none, return an empty list.

Examples

Input candidates = [5, 3, 8], target = 11
Output [[3, 3, 5], [3, 8]]
Why 3 + 3 + 5 and 3 + 8 both reach 11.
Input candidates = [4, 6], target = 7
Output []
Why every sum of 4s and 6s is even, so 7 cannot be reached.
Input candidates = [5], target = 15
Output [[5, 5, 5]]
Why one number can be reused: 5 + 5 + 5.

Constraints

Your answer must contain

Target Aim to stop a branch as soon as it passes the target. The work still grows quickly as the target gets larger than the smallest number.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Pick one number and ask the same question again. What does the target become?

Hint 2 the approach

A path ends when the remaining target is zero, or when it can no longer be reached. How can you tell the second case early?

Hint 3 the key step

Sort the numbers. Recurse with a start position and the target left. Stop at a number above it. Recurse from the same position, so a number can repeat.

Walkthrough

Full walkthrough brute force to best

Brute force

For each candidate, try every count from 0 up to target divided by that candidate, and add up each full choice of counts. With candidates c1, c2 and so on, that is the product of (target / c + 1) choices, and almost all of them are far over the target.

Best method

Sort the numbers. Keep the current combination, the remaining target and a start position. If the remaining target is 0, record a copy. Otherwise try each number from the start position on. Stop the loop at the first number larger than the remaining target, because every later number is larger still. Otherwise add the number and call again from the same position, not the next one, because a number may be used again. Add, recurse, remove. Never going back to an earlier position means each combination is built in increasing order only, so no set appears twice.

Hand trace

Run on [5, 3, 8] with target 11. Sort to [3, 5, 8]. Take 3 (left 8), take 3 (left 5), take 3 (left 2). The next number, 3, is more than 2, so stop. Back at left 5, take 5 (left 0) and record [3, 3, 5]. Then 8 is more than 5, so stop. Back at left 8, take 5 (left 3): 5 is more than 3, so stop. Take 8 (left 0) and record [3, 8]. Back at the top, take 5 (left 6), then 5 again (left 1): stop. 8 is more than 6, so stop. Take 8 (left 3): stop. The result is [[3, 3, 5], [3, 8]].

Code

def combination_sum(candidates, target):
    nums = sorted(candidates)
    out = []
    path = []
    def go(start, left):
        if left == 0:
            out.append(path[:])
            return
        for i in range(start, len(nums)):
            if nums[i] > left:
                break
            path.append(nums[i])
            go(i, left - nums[i])
            path.pop()
    go(0, target)
    return out

Time and memory

Time is the number of paths tried. A path has at most target / smallest candidate steps and each step has at most n choices, so the worst case is about n to the power of that depth. Extra memory is O(target / smallest candidate) for the path and the recursion, plus the answer.

Common mistakes

  • Recursing from the next position. That allows each number only once, so [3, 3, 5] is lost.
  • Starting every call at position 0. Then [3, 5] and [5, 3] both appear.
  • Not stopping when a number is larger than the remaining target. The search then goes far deeper than it needs to.

Related problems

More Backtracking problems
Combination Sum: hints, walkthrough and Python solution