Learn / Recursion and backtracking
Combination sum
Choose numbers that add up to a target, where order does not matter. Fixing an order of the candidates (and never going back to an earlier one) makes every combination appear once. Whether a candidate may be reused decides whether the recursion stays on index i or moves to i + 1.
How to recognise it
- The question asks for all combinations that sum to a target, with or without reuse.
- Two answers with the same numbers in a different order count as one.
- The candidates are small enough that the answer list is small.
The idea in one picture
Lay the candidates out in a row. Walk along the row deciding how many of each to take. You never walk back, so each combination is decided in exactly one way.
Three rules, three small changes
| Problem | Reuse? | Duplicates in input? | Change |
|---|---|---|---|
| Combination Sum | yes | no | "take" stays on i |
| Combination Sum II | no | yes | sort; skip equal values at the same depth; move to i + 1 |
| Combination Sum III | no | digits 1 to 9 | exactly k numbers; digits in increasing order |
Template (each candidate at most once, input may repeat)
sort c
function build(start, left, cur):
if left == 0: record a copy of cur; return
for i from start while i < n and c[i] <= left:
if i > start and c[i] == c[i - 1]: continue
add c[i]; build(i + 1, left - c[i], cur); remove it
Common mistakes
- Restarting the loop at 0 in every call, which produces every order of the same numbers.
- Removing duplicate answers with a set at the end instead of avoiding them.
- Forgetting the size rule in Combination Sum III.
Problems
- Combination Summediumguide ready
- Combination Sum IImediumguide ready
- Combination Sum IIImediumguide ready