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
Constraints
- 1 <= length of
candidates<= 8. - Each candidate is between 2 and 30, and all are different.
- 1 <=
target<= 50.
Your answer must contain
- The method; why a combination is not built twice; code; time and memory cost; a hand trace of example 1.
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 outTime 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.