Backtracking
Build candidates step by step and undo choices: subsets, permutations, puzzles.
6 pages, free to read
- 1
The backtracking template
IntermediateBacktracking builds a solution one choice at a time, explores each choice with recursion, and undoes it before trying the next, so it can search every valid answer without storing them all.
10 min read - 2
Subsets
IntermediateTo list every subset, decide for each element whether it is in or out; a set of n elements has 2^n subsets, and backtracking generates them in O(n * 2^n).
9 min read - 3
Permutations
IntermediateA permutation is an ordering of all the elements; n distinct elements have n! orderings, and backtracking builds them position by position using a used array.
9 min read - 4
Combinations & combination sum
IntermediateCombination problems pick unordered groups that meet a rule such as size k or a target sum; the start index prevents reordered duplicates, and a running remainder lets you stop early.
10 min read - 5
Constraint puzzles (N-Queens, Sudoku)
AdvancedConstraint puzzles fill a board one cell or row at a time, check the rules before each placement using fast lookup sets, and backtrack the moment a rule would be broken.
12 min read - 6
Pruning the search
AdvancedPruning cuts off branches of the search tree that cannot lead to a valid or better answer, which is what makes exponential backtracking fast enough in practice.
10 min read