Backtracking
Signal: "return all subsets / permutations / combinations / valid arrangements", puzzles (N-Queens, Sudoku), or a search over choices with constraints. Inputs are usually small (n ≤ ~15–20), because the output itself can be exponential.
Core idea: build a candidate one choice at a time. After exploring everything that follows a choice, undo it and try the next. Prune any branch that can no longer lead to a valid answer.
The template
python
def backtrack(state, choices):
if is_complete(state):
results.append(state.copy()) # copy! state keeps changing
return
for c in choices(state):
if not valid(state, c): # prune early
continue
state.append(c) # choose
backtrack(state, ...) # explore
state.pop() # un-chooseThree things to get right:
- What's the state, and when is it complete?
- What choices are available, and how do you avoid duplicates? Use a
startindex for combinations; sort and skip equal neighbors for duplicate inputs; use aused[]array for permutations. - Pruning: stop when the remaining sum is negative, when a queen is attacked, and so on.
| Problem type | Branching | Count |
|---|---|---|
| Subsets | include/exclude each element | 2ⁿ |
| Permutations | any unused element next | n! |
| Combinations of size k | elements after start | C(n, k) |