synopsis · Paradigms · chapter 31
Backtracking
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
DFS over a tree of partial answers: choose a piece, explore the rest, un-choose it. The undo lets one shared path serve every branch.
- use it when
"Return all …" (subsets, orders, partitions, boards) or "place under rules", with small n: about 20 for 2ⁿ, about 10 for n!.
- template
if (goal) { record a copy; return; }thenfor (choice) { choose; backtrack(next); un-choose; } - cost
Nodes × work per node. Subsets O(n·2ⁿ) · permutations O(n·n!) · k of n O(k·C(n, k)). Extra space = depth, O(n).
- trap
result.add(path)stores a reference that ends up empty. Alwaysresult.add(new ArrayList<>(path)). - trap
Duplicates: sort, then
if (i > start && a[i] == a[i - 1]) continue;. Withi > 0you lose answers like [1, 2, 2]. - pro tip
Order ignored → loop from
start. Order matters → loop from 0 withused[]. Reuse allowed → recurse withi, noti + 1. - pro tip
Prune before the call: sort +
break, a loop bound, O(1) attack tables. Need one answer? Returnbooleanand stop ontrue. - use it when
Asked to count or find a min/max, with n in the hundreds or more? That's DP, not backtracking.
Shaky on a card? Open the chapter or flip its recall cards.