Backtracking
Systematically explore every candidate by choosing, recursing and un-choosing — with pruning to make it fast enough.
Backtracking builds solutions one decision at a time. After each choice it recurses; if the partial solution can't lead anywhere valid, it undoes the last choice ("backtracks") and tries the next option. It's a depth-first search over the tree of decisions.
The template
backtrack(state):
if state is a complete solution: record it; return
for each choice available from state:
if choice is invalid: continue ← pruning
make the choice ← choose
backtrack(new state) ← explore
undo the choice ← un-chooseEvery backtracking problem is this template; only the choices, validity check and completion test differ.
Permutations, combinations, subsets
// Permutations of distinct numbers: n! results
List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
backtrack(nums, new ArrayList<>(), new boolean[nums.length], res);
return res;
}
void backtrack(int[] nums, List<Integer> path, boolean[] used, List<List<Integer>> res) {
if (path.size() == nums.length) { res.add(new ArrayList<>(path)); return; } // copy!
for (int i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true; path.add(nums[i]); // choose
backtrack(nums, path, used, res); // explore
path.remove(path.size() - 1); used[i] = false; // un-choose
}
}
// Combinations: choose k of 1..n
void combine(int start, int n, int k, List<Integer> path, List<List<Integer>> res) {
if (path.size() == k) { res.add(new ArrayList<>(path)); return; }
for (int i = start; i <= n - (k - path.size()) + 1; i++) { // prune: enough numbers left
path.add(i);
combine(i + 1, n, k, path, res);
path.remove(path.size() - 1);
}
}def permute(nums):
res, path, used = [], [], [False] * len(nums)
def bt():
if len(path) == len(nums):
res.append(path[:]) # copy!
return
for i, x in enumerate(nums):
if used[i]:
continue
used[i] = True; path.append(x) # choose
bt() # explore
path.pop(); used[i] = False # un-choose
bt()
return res
def combine(n, k):
res, path = [], []
def bt(start):
if len(path) == k:
res.append(path[:]); return
for i in range(start, n - (k - len(path)) + 2): # prune
path.append(i); bt(i + 1); path.pop()
bt(1)
return res
def subsets(nums):
res, path = [], []
def bt(i):
if i == len(nums):
res.append(path[:]); return
bt(i + 1) # exclude nums[i]
path.append(nums[i]); bt(i + 1); path.pop() # include nums[i]
bt(0)
return resfunction permute(nums: number[]): number[][] {
const res: number[][] = [], path: number[] = [];
const used = new Array(nums.length).fill(false);
const bt = () => {
if (path.length === nums.length) { res.push([...path]); return; }
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true; path.push(nums[i]);
bt();
path.pop(); used[i] = false;
}
};
bt();
return res;
}
function subsets(nums: number[]): number[][] {
const res: number[][] = [], path: number[] = [];
const bt = (start: number) => {
res.push([...path]); // every node is a subset
for (let i = start; i < nums.length; i++) {
path.push(nums[i]); bt(i + 1); path.pop();
}
};
bt(0);
return res;
}| Problem | Count | Time |
|---|---|---|
| Subsets | 2ⁿ | O(n · 2ⁿ) |
| Permutations | n! | O(n · n!) |
| Combinations C(n, k) | n! / (k!(n−k)!) | O(k · C(n, k)) |
Duplicates in the input? Sort first, then skip a choice equal to the previous one at the same depth: if (i > start && nums[i] == nums[i-1]) continue;.
Constraint problems: N-Queens and Sudoku
Place N queens so none attack each other. Choose a column for each row; prune any column or diagonal already attacked. Using sets (or bitmasks) for columns and both diagonals makes each validity check O(1).
int totalNQueens(int n) { return place(0, n, new boolean[n], new boolean[2 * n], new boolean[2 * n]); }
int place(int r, int n, boolean[] cols, boolean[] d1, boolean[] d2) {
if (r == n) return 1;
int count = 0;
for (int c = 0; c < n; c++) {
if (cols[c] || d1[r + c] || d2[r - c + n]) continue; // attacked → prune
cols[c] = d1[r + c] = d2[r - c + n] = true;
count += place(r + 1, n, cols, d1, d2);
cols[c] = d1[r + c] = d2[r - c + n] = false;
}
return count;
}def total_n_queens(n):
cols, d1, d2 = set(), set(), set()
def place(r):
if r == n:
return 1
count = 0
for c in range(n):
if c in cols or r + c in d1 or r - c in d2:
continue # attacked -> prune
cols.add(c); d1.add(r + c); d2.add(r - c)
count += place(r + 1)
cols.remove(c); d1.remove(r + c); d2.remove(r - c)
return count
return place(0)function totalNQueens(n: number): number {
const cols = new Set<number>(), d1 = new Set<number>(), d2 = new Set<number>();
const place = (r: number): number => {
if (r === n) return 1;
let count = 0;
for (let c = 0; c < n; c++) {
if (cols.has(c) || d1.has(r + c) || d2.has(r - c)) continue;
cols.add(c); d1.add(r + c); d2.add(r - c);
count += place(r + 1);
cols.delete(c); d1.delete(r + c); d2.delete(r - c);
}
return count;
};
return place(0);
}Making backtracking fast
- Prune early — reject partial solutions as soon as a constraint is violated (or a bound shows they can't beat the best so far: branch and bound).
- Order choices well — try the most constrained variable first (Sudoku: the cell with the fewest candidates).
- Use O(1) validity checks — sets, boolean arrays or bitmasks instead of rescanning.
- Memoize if identical sub-states recur — then it's really DP.
- Backtracking = DFS over a decision tree: choose → explore → un-choose.
- Record copies of the current path.
- Exponential by nature; pruning and good ordering make it practical.
- Sort + skip equal neighbours to avoid duplicate results.
QGenerate all valid combinations of n pairs of parentheses.medium
Backtrack with counts of open and close used: add '(' if open < n; add ')' if close < open. Complete when the length is 2n. The pruning guarantees every leaf is valid; the count is the n-th Catalan number.
QWord search: does a word exist in a grid of letters?medium
DFS from each cell matching the first letter; at each step move to a neighbour matching the next letter, temporarily marking the cell visited (e.g. overwrite it with '#') and restoring it on backtrack. O(cells · 4ᴸ) worst case.