Backtracking and Search (DSA Core #9)
Backtracking is depth-first search over the tree of partial solutions. You build a candidate one choice at a time, recurse, and undo the choice when you return. The code is short; the skill is knowing which branches to cut and when the search should have been a DP instead.
Recursion trees
Every backtracking problem has a tree whose nodes are partial states and whose children are the choices available from that state.
- Leaves are complete candidates: a full permutation, a placed set of queens, a filled board.
- Internal nodes are partial candidates.
- Depth is the number of decisions made so far.
The size of that tree is the cost:
\[ \text{subsets: } 2^n \text{ leaves}, \qquad \text{permutations: } n! \text{ leaves} \]
For N-Queens the unpruned tree is \(n^n\); pruning cuts it to a tiny fraction.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, rounded corners=3pt, minimum width=0.72cm, minimum height=0.5cm, font=\scriptsize},
a/.style={->, thick}]
\node[n, fill=blue!12] (r) at (0,0) {\{\}};
\node[n] (a) at (-2.1,-0.95) {\{1\}};
\node[n] (b) at (0,-0.95) {\{2\}};
\node[n] (c) at (2.1,-0.95) {\{3\}};
\node[n, fill=green!20] (aa) at (-2.8,-1.9) {\{1,2\}};
\node[n, fill=green!20] (ab) at (-1.4,-1.9) {\{1,3\}};
\node[n, fill=green!20] (ba) at (-0.7,-1.9) {\{2,3\}};
\node[n, fill=green!20] (bb) at (0.7,-1.9) {\{2,1\}};
\draw[a] (r) -- (a); \draw[a] (r) -- (b); \draw[a] (r) -- (c);
\draw[a] (a) -- (aa); \draw[a] (a) -- (ab);
\draw[a] (b) -- (ba); \draw[a] (b) -- (bb);
\node[font=\scriptsize, anchor=west] at (3.0,-1.3) {leaves = candidates};
\end{tikzpicture}
Two things make the tree smaller, and they are the whole technique:
- Pruning: cut a branch as soon as it cannot lead to a valid or better answer.
- Ordering: try the most constrained choices first, so contradictions appear early.
templates?
ASolution
Every template is just a rule for what the children of a node are: take/skip for subsets, an unused element for permutations, a row/column choice for boards. Once the children are clear, the code is a DFS.
Subsets
Include-or-skip, one binary decision per element:
void subsets(int i, const vector<int>& a, vector<int>& cur,
vector<vector<int>>& out) {
if (i == (int)a.size()) { out.push_back(cur); return; }
subsets(i + 1, a, cur, out); // skip a[i]
cur.push_back(a[i]);
subsets(i + 1, a, cur, out); // take a[i]
cur.pop_back(); // undo
}
With duplicates, sort first and skip a repeated value at the same decision level:
void subsetsUnique(int i, const vector<int>& a, vector<int>& cur,
vector<vector<int>>& out) {
out.push_back(cur);
for (int j = i; j < (int)a.size(); ++j) {
if (j > i && a[j] == a[j - 1]) continue; // same value already tried here
cur.push_back(a[j]);
subsetsUnique(j + 1, a, cur, out);
cur.pop_back();
}
}
The skip condition j > i && a[j] == a[j-1] is per level, not global. It says
“within this loop, do not start a branch with a value you already started a
branch with”. That is what prevents duplicate subsets without a set.
Bitmask enumeration is the iterative alternative:
for (int mask = 0; mask < (1 << n); ++mask) {
vector<int> pick;
for (int i = 0; i < n; ++i) if (mask & (1 << i)) pick.push_back(a[i]);
out.push_back(pick);
}
\(O(2^n \cdot n)\) time, no recursion. Fine for \(n \le 20\).
j > i rather than j > 0?ASolution
i is where this level’s choices start. Skipping against earlier positions
outside the loop would wrongly remove valid first occurrences.
Permutations
Two standard formulations: swap in place, or a used array.
void permute(vector<int>& a, int k, vector<vector<int>>& out) {
if (k == (int)a.size()) { out.push_back(a); return; }
for (int i = k; i < (int)a.size(); ++i) {
swap(a[k], a[i]);
permute(a, k + 1, out);
swap(a[k], a[i]); // restore
}
}
The swap version generates each permutation once and uses \(O(n)\) extra space for
the recursion. With duplicates, sorting plus a per-level seen check is needed:
void permuteUnique(vector<int>& a, int k, vector<vector<int>>& out) {
if (k == (int)a.size()) { out.push_back(a); return; }
unordered_set<int> used;
for (int i = k; i < (int)a.size(); ++i) {
if (used.count(a[i])) continue;
used.insert(a[i]);
swap(a[k], a[i]);
permuteUnique(a, k + 1, out);
swap(a[k], a[i]);
}
}
The used set is per recursive call, so it only prevents picking the same value
twice at the same depth. A global used array would forbid valid permutations.
The next_permutation loop is the iterative answer when the task is “all
permutations in lexicographic order”:
sort(a.begin(), a.end());
do { out.push_back(a); } while (next_permutation(a.begin(), a.end()));
ASolution
At depth k, position k is fixed to each remaining element exactly once, and
the suffix is permuted recursively. The choices partition the solution set.
Combinations
Choose k of n, unordered, so each element is considered once and order does
not matter. The start index enforces that.
void combine(int start, int k, const vector<int>& a, vector<int>& cur,
vector<vector<int>>& out) {
if (k == 0) { out.push_back(cur); return; }
for (int i = start; i + k <= (int)a.size(); ++i) { // room left for k picks
cur.push_back(a[i]);
combine(i + 1, k - 1, a, cur, out);
cur.pop_back();
}
}
i + k <= n is a pruning condition: if fewer than k elements remain, no
completion exists. Removing it still gives correct answers, just more calls.
Combination sum with repetition allows combine(i, ...) instead of i + 1.
Combination sum with duplicates needs the same per-level skip as subsets.
combine(i + 1, ...) andcombine(i, ...)?
ASolution
i + 1 moves past the chosen element, so each element is used at most once.
i allows choosing it again, which is the “unlimited reuse” variant.
N-Queens
Place n queens so no two share a row, column, or diagonal. One queen per row is
forced, so the decision is the column for each row.
int solve(int row, int n, int cols, int diag1, int diag2) {
if (row == n) return 1;
int count = 0;
int free = ((1 << n) - 1) & ~(cols | diag1 | diag2);
while (free) {
int bit = free & -free; // lowest set bit
free -= bit;
count += solve(row + 1, n, cols | bit,
((diag1 | bit) << 1) & ((1 << n) - 1),
(diag2 | bit) >> 1);
}
return count;
}
The bitmasks encode the three attack directions: cols for columns, diag1 for
the / diagonals (shifted left each row), diag2 for \ diagonals (shifted
right). free & -free extracts one candidate, and the loop tries each.
Pruning is total: an attacked cell is never entered. Without it the search is \(n^n\); with it, \(n = 8\) takes a few thousand nodes and \(n = 12\) about 14 million.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
s/.style={draw, thick, minimum size=0.62cm, font=\scriptsize}]
\fill[gray!20] (0,0) rectangle (0.62,-0.62);
\fill[gray!20] (0.62,-0.62) rectangle (1.24,-1.24);
\fill[gray!20] (1.24,0) rectangle (1.86,-0.62);
\fill[gray!20] (1.86,-0.62) rectangle (2.48,-1.24);
\draw[step=0.62, thick, black!45] (0,0) grid (2.48,-2.48);
\node[circle, fill=black!75, text=white, inner sep=1.6pt, font=\scriptsize\bfseries] at (0.31,-0.31) {Q};
\node[circle, fill=black!75, text=white, inner sep=1.6pt, font=\scriptsize\bfseries] at (1.55,-0.93) {Q};
\node[circle, fill=black!75, text=white, inner sep=1.6pt, font=\scriptsize\bfseries] at (0.93,-1.55) {Q};
\node[circle, fill=black!75, text=white, inner sep=1.6pt, font=\scriptsize\bfseries] at (2.17,-2.17) {Q};
\node[font=\scriptsize, anchor=west] at (2.8,-1.1) {4-queens: one valid placement};
\end{tikzpicture}
diag1 shifted left and diag2 shifted right?ASolution
Moving down one row moves both diagonal attacks one column sideways. The two diagonals go in opposite directions, so one mask shifts left and the other right.
Sudoku-style constraint search
Sudoku is backtracking with three constraint sets per cell: row, column, and 3×3 box. Bitmasks make the feasibility test \(O(1)\).
bool solveSudoku(vector<string>& g) {
int row[9] = {}, col[9] = {}, box[9] = {};
for (int r = 0; r < 9; ++r)
for (int c = 0; c < 9; ++c) {
if (g[r][c] == '.') continue;
int bit = 1 << (g[r][c] - '1');
row[r] |= bit; col[c] |= bit; box[(r / 3) * 3 + c / 3] |= bit;
}
function<bool()> go = [&]() -> bool {
int br = -1, bc = -1, best = 10; // MRV: fewest candidates
for (int r = 0; r < 9; ++r)
for (int c = 0; c < 9; ++c) {
if (g[r][c] != '.') continue;
int used = row[r] | col[c] | box[(r / 3) * 3 + c / 3];
int cnt = 9 - __builtin_popcount(used);
if (cnt < best) { best = cnt; br = r; bc = c; }
}
if (br == -1) return true; // no empty cell
int used = row[br] | col[bc] | box[(br / 3) * 3 + bc / 3];
for (int d = 0; d < 9; ++d) {
int bit = 1 << d;
if (used & bit) continue;
g[br][bc] = char('1' + d);
row[br] |= bit; col[bc] |= bit; box[(br / 3) * 3 + bc / 3] |= bit;
if (go()) return true;
row[br] &= ~bit; col[bc] &= ~bit; box[(br / 3) * 3 + bc / 3] &= ~bit;
g[br][bc] = '.';
}
return false;
};
return go();
}
Choosing the most constrained cell (minimum remaining values) is the difference between milliseconds and seconds on hard puzzles. It is the same “most constrained first” rule as N-Queens.
General constraint search: variables, domains, constraints. Order by smallest domain, prune as soon as a constraint is violated, and only then recurse.
ASolution
The masks are the constraint state. A value left in a mask after returning makes later branches think that digit is still used in that row, column, or box.
Pruning
Pruning is what makes backtracking usable. Four kinds:
- Feasibility: a partial assignment already violates a constraint. Stop. (N-Queens attacks, Sudoku duplicates.)
- Bound: the partial solution cannot beat the best found. Stop. (Branch-and-bound knapsack, “maximum sum with at most k picks”.)
- Completeness: not enough remaining elements to finish. Stop.
(
i + k <= nabove.) - Symmetry: two branches are equivalent, so only one is explored. (Sorting before duplicate skips, fixing the first element.)
A bound needs an optimistic estimate. If best is the best complete answer so
far, and current + optimisticRemaining <= best, the branch cannot improve it.
void search(int i, int value, int weight) { // 0/1 knapsack bound
if (weight > W) return; // feasibility
best = max(best, value);
if (i == n) return;
if (value + upperBound(i) <= best) return; // bound
search(i + 1, value + v[i], weight + w[i]); // take
search(i + 1, value, weight); // skip
}
Ordering the items by value density makes the bound tight early, which prunes more. Without a bound, branch-and-bound is just brute force with extra steps.
ASolution
If it underestimates the remaining value, you may prune a branch that would have won. An upper bound (fractional knapsack, ignoring constraints) is safe because the true value can only be lower.
Backtracking versus DP
Both explore states. The difference is whether states merge.
- Backtracking when the answer needs the actual sequences and states do not merge, or when the search space is small (\(n \le 20\)).
- DP when many partial solutions reach the same state, so you can compute it once.
“Count paths in a grid” is DP: (i, j) is reached by many prefixes, and only the
count matters. “Print all paths” is backtracking: the prefixes are the output.
Counting N-Queens solutions has no compact state, so it stays search.
Duplicates are the visible sign of mergeable states: the moment two different prefixes leave the same remaining problem, memoization or tabulation applies.
// backtracking: enumerate each subset
void gen(int i, int sum, ...);
// DP: count subsets with a given sum, states merge on (i, sum)
bool dp[n + 1][target + 1];
ASolution
Check whether two different histories can reach the same state. If yes, count the state once and multiply; if the count depends on the history, search.
Bugs and edge cases
- Forgetting to undo. Push without pop, set without reset. The next branch sees polluted state.
- Pruning too hard. A bound that is not optimistic, or a duplicate skip that removes a distinct answer.
- Global
visited. In permutations and subsets the used-set must be per path, not global. - Modifying the input. Swapping is fine if you swap back; sorting changes the caller’s data.
- Output duplication. Duplicate handling must be per decision level.
- Stack depth. Depth
nfor \(n = 20\) is fine; depth \(10^5\) is not. - Copy cost.
out.push_back(cur)copies; reserve or move where it matters. - Empty input.
[[]]for subsets versus[]— read the expected shape.
What is the likely cause?
ASolution
Either duplicate values are not skipped per level, or the recursion advances by
start + 1 while scanning from start, which revisits the same choices.
Next: Bit Manipulation (DSA Core #10) — the operations, the tricks, and signed versus unsigned.