The pattern: backtracking
Master state-space tree exploration, the Choose-Explore-Unchoose template, duplicate pruning, and constraint satisfaction for permutations and combinations.
Backtracking is systematic depth-first search through the decision tree of a problem. Whenever the algorithm determines that the current partial candidate cannot possibly be completed to a valid solution, it abandons (prunes) that candidate and "backtracks" to try the next alternative.
The entire pattern revolves around a simple, unbreakable three-step rhythm:
choose(option)
explore(next_state)
un-choose(option) # restore original state (backtrack)01The core templates
1. Subsets / Power Set (Include vs. Exclude)
For each element, you decide whether to include it or exclude it, yielding 2^n states:
build(start, cur):
record copy of cur
for i from start to n - 1:
cur.add(nums[i]) # Choose
build(i + 1, cur) # Explore
cur.removeLast() # Un-chooseUsed for: Subsets, Subsets II, Letter Case Permutation.
2. Combinations (Fixed Size k or Target Sum)
Combinations select elements without regard to order ([1, 2] is the same as [2, 1]). Enforce strictly increasing indices using start to avoid permutations:
build(start, cur, target):
if target == 0: record copy; return
for i from start to n - 1:
if nums[i] > target: break # Prune
cur.add(nums[i])
build(i + 1, cur, target - nums[i])
cur.removeLast()Used for: Combinations, Combination Sum, Combination Sum II, Combination Sum III.
3. Permutations (Order Matters)
Permutations arrange all elements where ordering matters ([1, 2] is distinct from [2, 1]). Track which elements have been placed using a boolean[] used array:
build(cur):
if cur.size() == n: record copy; return
for i from 0 to n - 1:
if used[i]: continue
used[i] = true ; cur.add(nums[i])
build(cur)
used[i] = false ; cur.removeLast()Used for: Permutations, Permutations II.
4. Duplicate Pruning (The "Twins in Line" Rule)
When the input contains duplicate numbers (e.g. [1, 2, 2]), sorting the array upfront brings identical elements together:
- In subsets / combinations: Skip if
i > start && nums[i] == nums[i - 1]. - In permutations: Skip if
i > 0 && nums[i] == nums[i - 1] && !used[i - 1].
This ensures identical twins are only selected in their original relative index order, preventing duplicate solution branches.
5. Grid Pathfinding & Constraint Satisfaction
In 2D boards and chess problems (Word Search, N-Queens), cells or diagonals are marked before recursing and restored immediately upon return.
Used for: Word Search, N-Queens.
02The golden rules
- Always make a deep copy before recording. In Java,
res.add(new ArrayList<>(cur))copies the current state. Addingres.add(cur)stores a reference to a mutable list that empties at the end. - Sort early to prune. Sorting allows early termination (
if (nums[i] > target) break) and simplifies duplicate detection. - Always unchoose. Every modification to shared state (
cur.add,used[i] = true,board[r][c] = '#') must have an exact inverse immediately after the recursive call.