Pattern #15
Backtracking
EssentialChoose, explore, undo. Build all valid combinations or search with pruning.
When to use
You must generate all solutions (subsets, permutations, combinations) or search a decision tree with constraints.
Recognition cues
- Subsets / permutations / combinations
- Word search / N-Queens style constraints
- Path building with undo
Common pitfalls
- Forgetting to undo (mutate path without pop)
- Wrong start index causing duplicates or misses
- Not pruning when the partial path is already invalid
90-second recognition drill
Which pattern fits best?
- Subsets / permutations / combinations
- Word search / N-Queens style constraints
- Path building with undo
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
Step 1 of 8
stack
∅
Statepath=[]choices=[1, 2, 3]
path = []
How to think about it
At each step, try a choice, recurse, then undo. The call stack is the current path. Prune when the partial solution cannot lead to a valid complete one. Order choices carefully to avoid duplicate outputs.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Reuse combinations | After taking candidates[i], the next call keeps start index i. Record a copy when the remainder hits 0. Skip a candidate larger than the remainder |
LC 39 |
| Permutations | A used[] flag per index. Append an unused value, recurse, then pop and clear the flag. Record the path when its length is n |
LC 46 |
| Subsets | Record the path on entry, because every prefix is an answer. Then try each j ≥ start, append nums[j], recurse at j + 1, and pop |
LC 78 |
| Word search | Mark the cell, try the four neighbors for the next character, then write the original letter back | LC 79 |
| Unique subsets | Sort first. At one start index, skip nums[i] when i > start and it equals nums[i - 1] |
LC 90 |
| Palindrome cuts | From start, extend end only while s[start..end] is a palindrome. Recurse at end + 1. Record the path when start == n |
LC 131 |
Complexity baseline
Output-sensitive: often O(n·#solutions). Extra space O(n) recursion depth.
From template to problem
- Say when a path is recorded: on entry for subsets (LC 78), at length
nfor permutations (LC 46), at remainder 0 for combinations (LC 39), atstart == nfor cuts (LC 131). - The start index is what kills duplicate order. Subsets advance it (LC 78). Combination sum keeps it so a value can repeat (LC 39).
- Undo every mutation before the next branch. The board cell is restored (LC 79), and the used flag is cleared (LC 46).
- After sorting, a duplicate value is skipped only when the previous copy at this depth was not chosen (LC 90).
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
Backtracking · Template
/** Backtracking template: subsets (choose / skip via start index). */
export function subsets(nums: number[]): number[][] {
const res: number[][] = [];
const path: number[] = [];
const dfs = (start: number) => {
res.push([...path]);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]!);
dfs(i + 1);
path.pop();
}
};
dfs(0);
return res;
}
/** Backtracking template: subsets (choose / skip via start index). */
export function subsets(nums: number[]): number[][] {
const res: number[][] = [];
const path: number[] = [];
const dfs = (start: number) => {
res.push([...path]);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]!);
dfs(i + 1);
path.pop();
}
};
dfs(0);
return res;
}
#StatusProblemTypeDifficultyDone
- 1#39 Combination SumGuidemedium
- 2#46 PermutationsGuidemedium
- 3#78 SubsetsGuidemedium
- 4#79 Word SearchGuidemedium
- 5#90 Subsets IIGuidemedium
- 6#131 Palindrome PartitioningGuidemedium