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

ProblemReuse?Duplicates in input?Change
Combination Sumyesno"take" stays on i
Combination Sum IInoyessort; skip equal values at the same depth; move to i + 1
Combination Sum IIInodigits 1 to 9exactly 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

0 of 3 solved

Check yourself

In Combination Sum, where a candidate may be reused, which index does the "take it" branch recurse on?

Why does always moving forward through the candidates prevent duplicate combinations like [2, 3] and [3, 2]?

In Combination Sum II, the candidates are sorted. Why can the loop stop as soon as c[i] exceeds what is left?