Learn the pattern · ~15 min
Backtracking
also called DFS with undo, constraint search, pruning
Build the answer one choice at a time, check the rules before each choice, and undo it when you come back, so a dead prefix dies before it grows.
Reach for it when you read
- +"Find all valid arrangements / placements / paths", and n is small.
- +Each step has a few choices, and an early choice can make a later one impossible.
- +A partial answer can be rejected before it is finished (unbalanced prefix, attacked queen, bad cut).
- +Fill a board or buckets to satisfy rules (sudoku, k equal-sum subsets).
Not this one when
- ×Every subset or ordering with no rules between choices: plain subsets/permutations.
- ×Only a count or the best value, with overlapping subproblems: DP.
- ×A shortest path on a grid: BFS, not all paths.
Learn Backtracking
First, what does "backtracking" mean?
To backtrack is to go back the way you came. You build an answer one choice at a time. The moment the partial answer can't be finished, you step back to the last choice and try its next option.
Every step is the same three moves:
- do a choice (add it to the partial answer),
- explore everything that can follow it,
- undo it, so the next option starts from a clean state.
How does it look on a small case?
Build every balanced string of n = 2 pairs of brackets. Balanced means every ) closes an earlier (. Count how many of each you've used, open and close. The rule:
A
(is allowed whileopen < n. A)is allowed only whileclose < open.
Try ( before ), and follow the prefixes in the order the search visits them:
| prefix | open, close | what happens |
|---|---|---|
| (empty) | 0, 0 | ) would close nothing: only ( |
( |
1, 0 | both allowed; try ( first |
(( |
2, 0 | open = n, so only ) |
(() |
2, 1 | only ) |
(()) |
2, 2 | full length: record it, then undo back to ( |
() |
1, 1 | ) would close nothing: only ( |
()( |
2, 1 | only ) |
()() |
2, 2 | full length: record it; undo all the way, done |
Two answers from 8 prefixes, out of 31 strings of length 0 to 4. A pruned prefix such as ) or ()) is never extended.
The code for it
void gen(int n, int open, int close, string& cur, vector<string>& res) {
if ((int)cur.size() == 2 * n) { res.push_back(cur); return; }
for (char c : {'(', ')'}) {
bool allowed = (c == '(') ? open < n : close < open; // prune
if (!allowed) continue;
cur.push_back(c); // do
gen(n, open + (c == '('), close + (c == ')'), cur, res); // explore
cur.pop_back(); // undo
}
}You don't need to memorise this. It's the table: for each allowed character, add it, go deeper, take it back.
Why pop_back() after the call? Because cur is one shared string. After (()) is recorded, the search is back at ( and wants to try ) there. Without the undo it would still hold (()). Undo exactly what you did, or the next branch starts dirty.
Fine, but how does this help us?
The classic problem: N-Queens. Put n queens on an n × n board so that no two share a row, a column or a diagonal.
For n = 4, by hand. Each row gets exactly one queen, so an answer is a list of columns, row by row.
| row | try columns 0, 1, 2, 3 | how you decide |
|---|---|---|
| 0 | 0 | first free column |
| 1 | 2 | 0 is the same column, 1 is diagonal to 0:0 |
| 2 | none | every column is attacked: go back, move row 1 to 3 |
| 2 | 1 | with 0:0 and 1:3, column 1 is safe |
| 3 | none | every column is attacked: row 0 itself must move |
| 0 | 1 | start over with the queen at column 1 |
| 1, 2, 3 | 3, 0, 2 | the first safe column each time: a full board |
That's [1, 3, 0, 2]. Keep going and you find the only other one, [2, 0, 3, 1].
The brute force
Give every row every column, and check the whole board only at the end.
void fill(int r) { // every column for every row, check at the end
if (r == n) { if (ok(qcol)) sols.push_back(qcol); return; }
for (int c = 0; c < n; c++) { qcol[r] = c; fill(r + 1); }
}That's nⁿ boards: for n = 8, 8⁸ = 16,777,216. LeetCode allows n = 9: 9⁹ ≈ 3.9 × 10⁸ boards. Even if the check stops at the first clash, n = 9 alone took about 1 second (measured), borderline on a judge. Each extra row multiplies that by n: n = 10 means 10¹⁰ boards. Too slow.
The one thought that fixes it
Stop at the moment the queens sit at 0:0 and 1:2. Every column of row 2 is attacked: column 0 by the first queen, columns 1 and 3 by the second's diagonals, column 2 by its column.
The brute force doesn't notice: it fills rows 2 and 3 in 4 × 4 = 16 ways, and all 16 boards fail for the same reason.
So check each queen the moment you place it, against the rows above (the rows below are empty). If it's attacked, don't place it. If a row has no safe column, an earlier choice was wrong: undo it and move that queen on. That's do, explore, undo, with the check as the prune.
The check must be fast. A queen at row r, column c owns its column, the diagonal where r + c is constant, and the one where r − c is. Three arrays of flags make it O(1). (r − c can be negative, so add n − 1.)
void place(int r) {
if (r == n) { sols.push_back(qcol); return; } // every row has a queen
for (int c = 0; c < n; c++) {
if (col[c] || d1[r + c] || d2[r - c + n - 1]) continue; // attacked from above
col[c] = d1[r + c] = d2[r - c + n - 1] = true; // do
qcol[r] = c;
place(r + 1); // explore
col[c] = d1[r + c] = d2[r - c + n - 1] = false; // undo
}
}Dry run
n = 4. Every placement and every undo, in order:
| queens (row:col) | filling row | what happens |
|---|---|---|
| 0:0 | 1 | columns 0, 1 attacked; place at 2 |
| 0:0, 1:2 | 2 | all 4 attacked: undo 1:2, try row 1's next column |
| 0:0, 1:3 | 2 | column 1 is safe: place it |
| 0:0, 1:3, 2:1 | 3 | all 4 attacked: undo 2:1, then 1:3, then 0:0 |
| 0:1 | 1, 2, 3 | safe columns 3, 0, 2: answer [1, 3, 0, 2] |
| 0:2 | 1, 2, 3 | safe columns 0, 3, 1: answer [2, 0, 3, 1] |
| 0:3 | 1, 2, 3 | 1:0 (then 2:2) and 1:1 both hit a row with no room |
[1, 3, 0, 2] and [2, 0, 3, 1], the same answers as the brute force, from 17 calls instead of 256 boards.
Why it's fast enough
Count the choices: row 0 has n columns, row 1 at most n − 1 free ones, row 2 at most n − 2, so there are at most about n! full boards, with O(n) work per call. The prune does far better: n = 8 makes 2,057 calls to find all 92 answers, and n = 9 makes 8,394 for 352. The recursion is n deep: O(n) extra space.
From 1.7 × 10⁷ boards to about 2,000 calls, by refusing to build on a board that's already broken.
A sum budget? Break when it's too big
Combination Sum II: pick numbers (each once) that add up to a target. Sort, and carry what's left. Once a candidate is bigger than what's left, every later one is too:
if (c[i] > left) break; // sorted: everything after is too big too
if (i > start && c[i] == c[i - 1]) continue; // same-level duplicate[10, 1, 2, 7, 6, 1, 5] with target 8 gives [1, 1, 6] [1, 2, 5] [1, 7] [2, 6].
A path on a grid? Mark and unmark
Word Search: can you trace a word through neighbouring cells, each cell used once? The choices are the 4 neighbours. "Do" marks the cell, "undo" puts its letter back:
char keep = B[r][c];
B[r][c] = '#'; // do: this cell is in the path now
bool found = dfs(r + 1, c, w, k + 1) || dfs(r - 1, c, w, k + 1) ||
dfs(r, c + 1, w, k + 1) || dfs(r, c - 1, w, k + 1); // explore
B[r][c] = keep; // undoOn the board ABCE / SFCS / ADEE, "ABCCED" and "SEE" are found; "ABCB" isn't, because the B would be used twice.
One answer is enough? Return true
Sudoku Solver wants one filled board. Make the function return bool; when a call returns true, return true at once, without undoing, so the board keeps the answer.
Remember this
- Do, explore, undo. Undo exactly what you did, or it leaks into the next branch.
- Prune only prefixes that can never be finished; a wrong prune loses answers.
- Check against what's already placed, not what's still empty (rows above, not below).
- Whenever a problem asks for "every way to build something under rules", with small n, it's backtracking.
Practise it on Generate Parentheses, then Combination Sum II (a sum budget), Word Search (mark and unmark), Palindrome Partitioning (cutting a string), N-Queens and Sudoku Solver (stop at the first answer).
Below, watch Generate Parentheses run line by line.
Watch it work, line by line
Generate Parentheses ↗, n = 3 → ((())), (()()), (())(), ()(()), ()()(). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 4 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Can I build the answer one choice at a time, and can I tell that a half-built answer is already doomed before finishing it?
Reach for it when
- +place items under constraints (N-Queens, Sudoku)
- +grid word search
- +partition a string into valid pieces
- +generate valid structures (parentheses)
- +small n or heavy pruning; exponential worst case
It fails when
- ×Only a count or optimum is needed and subproblems overlapuse Memoise it: DP
- ×The used-set state repeats across pathsuse Memoise on the mask: bitmask DP
- ×A provable greedy or formula existsuse Greedy; don't explore a tree you don't need
- ×Huge state space, weak pruning, and you need one answer fastuse BFS or heuristics
Looks like it, isn't (and the other way round)
- Word Ladder looks like Backtracking, needs Graph BFS / DFS
Shortest transformation sequence is BFS on an implicit graph.
- Word Break looks like Backtracking, needs 1D / Fibonacci-style
Backtracking repeats suffixes; dp over prefix positions.
- Palindrome Partitioning II looks like Backtracking, needs Palindromic Substrings
Only the minimum cut is needed: palindrome table + 1D cut DP.
- Tallest Billboard looks like Backtracking, needs 0/1 Knapsack
3n assignments collapse into dp[difference] = best shorter-side height (the editorial also shows meet-in-the-middle).
Why this pattern and not another
You must enumerate all valid configurations (or find one) by building incrementally and abandoning dead branches early — choose, recurse, un-choose, with pruning.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What are the three moves inside every backtracking loop?Reveal
Choose, explore (recurse), un-choose. The undo is the exact reverse of the choice.
2Where does the validity check go, and why?Reveal
Before the recursive call. Then a dead prefix is cut together with its whole subtree, instead of being filtered at every leaf.
3When should backtracking become DP?Reveal
When you only need a count or the best value and the same state (index, remaining, mask) is reached by many paths. Memoise it.
Practice ladder
- 1Generate Parenthesesthe hookMedium
- 2Combination Sum IIa sum budgetMedium
- 3Word Searchpaths on a gridMedium
- 4Palindrome Partitioningcutting a stringMedium
- 5Restore IP Addressescutting with rulesMedium
- 6Partition to K Equal Sum Subsetsfilling bucketsMedium
- 7N-Queensplacement with O(1) checksHard
- 8Sudoku Solverstop at the first answerHard
Finished Backtracking? Mark it done and Lessgo moves you to the next step.