Recursion & Backtracking
Core idea
Section titled “Core idea”Backtracking is DFS over a decision tree. At each step you choose an option, explore further, then un-choose (undo) so the next option starts from a clean state.
Ask yourself three questions out loud:
- What’s my state? (the current path, the start index, a used[] array)
- What are my choices at this step?
- When do I stop/record? (the base case) and what can I prune?
Template
Section titled “Template”List<List<Integer>> result = new ArrayList<>();
void backtrack(int start, List<Integer> path, int[] nums) { if (/* goal reached */ true) { result.add(new ArrayList<>(path)); // COPY. Never add 'path' itself return; } for (int i = start; i < nums.length; i++) { if (/* invalid or prune */ false) continue; path.add(nums[i]); // choose backtrack(i + 1, path, nums); // explore (i+1: no reuse, i: reuse allowed) path.remove(path.size() - 1); // un-choose }}Complexity cheat sheet: subsets O(n · 2^n), permutations O(n · n!), combinations C(n, k) · k.
Problems
Section titled “Problems”Problem: Subsets (Medium) — LC 78
Approach (say out loud): “Each node of the recursion tree is a valid subset, so I record at every call, not just at the leaves. I loop from start so I only pick elements going forward, which avoids duplicates like [1,2] and [2,1].”
Java:
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> res = new ArrayList<>(); backtrack(0, nums, new ArrayList<>(), res); return res; }
private void backtrack(int start, int[] nums, List<Integer> path, List<List<Integer>> res) { res.add(new ArrayList<>(path)); for (int i = start; i < nums.length; i++) { path.add(nums[i]); backtrack(i + 1, nums, path, res); path.remove(path.size() - 1); } }}Complexity: O(n · 2^n) time, O(n) recursion space (plus output)
Edge cases: an empty input → [[]]. Subsets II (LC 90), with duplicates: sort first and add if (i > start && nums[i] == nums[i - 1]) continue;.
Problem: Permutations (Medium) — LC 46
Approach (say out loud): “Order matters, so at each position I can pick any unused element. I track used elements with a boolean array. I record when the path length equals n.”
Java:
class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<>(); backtrack(nums, new boolean[nums.length], new ArrayList<>(), res); return res; }
private void backtrack(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> res) { if (path.size() == nums.length) { res.add(new ArrayList<>(path)); return; } for (int i = 0; i < nums.length; i++) { if (used[i]) continue; used[i] = true; path.add(nums[i]); backtrack(nums, used, path, res); path.remove(path.size() - 1); used[i] = false; } }}Complexity: O(n · n!) time, O(n) space (plus output)
Edge cases: a single element. Permutations II (LC 47): sort, then skip when i > 0 && nums[i] == nums[i-1] && !used[i-1].
Problem: Combination Sum (Medium) — LC 39
Approach (say out loud): “Numbers can be reused, so I recurse with i, not i + 1. I subtract from the remaining target. If it hits 0, I record. If I sort first, I can break as soon as a number exceeds the remainder.”
Java:
class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> res = new ArrayList<>(); backtrack(candidates, target, 0, new ArrayList<>(), res); return res; }
private void backtrack(int[] c, int remain, int start, List<Integer> path, List<List<Integer>> res) { if (remain == 0) { res.add(new ArrayList<>(path)); return; } for (int i = start; i < c.length; i++) { if (c[i] > remain) break; // sorted, so everything after is too big path.add(c[i]); backtrack(c, remain - c[i], i, path, res); // i: reuse allowed path.remove(path.size() - 1); } }}Complexity: exponential, roughly O(n^(target/min)). O(target/min) recursion depth.
Edge cases: no combination → empty list. Combination Sum II (LC 40): each number used once (i + 1), and skip duplicates with i > start && c[i] == c[i-1].
Problem: Generate Parentheses (Medium) — LC 22
Approach (say out loud): “I build the string character by character. I can add ‘(’ if I’ve used fewer than n. I can add ‘)’ only if there are more opens than closes. That pruning guarantees every result is valid.”
Java:
class Solution { public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<>(); build(new StringBuilder(), 0, 0, n, res); return res; }
private void build(StringBuilder sb, int open, int close, int n, List<String> res) { if (sb.length() == 2 * n) { res.add(sb.toString()); return; } if (open < n) { sb.append('('); build(sb, open + 1, close, n, res); sb.deleteCharAt(sb.length() - 1); } if (close < open) { sb.append(')'); build(sb, open, close + 1, n, res); sb.deleteCharAt(sb.length() - 1); } }}Complexity: O(4^n / √n) results (the Catalan number), O(n) depth
Edge cases: n = 1 → ["()"].
Problem: Word Search (Medium) — LC 79
Approach (say out loud): “Try every cell as a starting point. DFS into the 4 neighbors, matching the word one character at a time. To avoid reusing a cell, I temporarily overwrite it with ‘#’ and restore it after (the backtrack step).”
Java:
class Solution { public boolean exist(char[][] board, String word) { for (int r = 0; r < board.length; r++) { for (int c = 0; c < board[0].length; c++) { if (dfs(board, word, 0, r, c)) return true; } } return false; }
private boolean dfs(char[][] board, String word, int idx, int r, int c) { if (idx == word.length()) return true; if (r < 0 || c < 0 || r >= board.length || c >= board[0].length) return false; if (board[r][c] != word.charAt(idx)) return false;
char saved = board[r][c]; board[r][c] = '#'; // mark visited boolean found = dfs(board, word, idx + 1, r + 1, c) || dfs(board, word, idx + 1, r - 1, c) || dfs(board, word, idx + 1, r, c + 1) || dfs(board, word, idx + 1, r, c - 1); board[r][c] = saved; // un-choose return found; }}Complexity: O(m · n · 3^L) time, where L = word length (3 because you don’t go back the way you came). O(L) space.
Edge cases: a word longer than the number of cells, a single-cell board, a word needing the same cell twice (not allowed).
Problem: N-Queens (Hard) — LC 51 (brief)
Approach (say out loud): “Place one queen per row. For each column in the current row, check whether the column or either diagonal is taken. I track these with three sets: columns, r - c (one diagonal direction), and r + c (the other). Choose, recurse to the next row, un-choose.”
Java:
class Solution { public List<List<String>> solveNQueens(int n) { List<List<String>> res = new ArrayList<>(); char[][] board = new char[n][n]; for (char[] row : board) Arrays.fill(row, '.'); place(0, n, board, new boolean[n], new boolean[2 * n], new boolean[2 * n], res); return res; }
private void place(int r, int n, char[][] board, boolean[] cols, boolean[] diag, boolean[] anti, List<List<String>> res) { if (r == n) { List<String> snapshot = new ArrayList<>(); for (char[] row : board) snapshot.add(new String(row)); res.add(snapshot); return; } for (int c = 0; c < n; c++) { int d = r - c + n, a = r + c; // +n keeps the index non-negative if (cols[c] || diag[d] || anti[a]) continue; cols[c] = diag[d] = anti[a] = true; board[r][c] = 'Q'; place(r + 1, n, board, cols, diag, anti, res); board[r][c] = '.'; cols[c] = diag[d] = anti[a] = false; } }}Complexity: O(n!) time roughly, O(n²) space for the board
Edge cases: n = 1 → one solution. n = 2 and n = 3 → no solutions.