Recursion and Backtracking
Backtracking Template from labuladong
def backtrack(nums, start, track):
# End condition
if (end condition):
result.append(track[:]) # copy, or every result aliases the same list
return
for i in range(start, len(nums)):
track.append(nums[i])
backtrack(nums, i + 1, track)
track.pop()
Time Complexity: O(N!).
Space Complexity: O(n).
For more details on time and space complexity, read this post: https://stackoverflow.com/questions/65526515/how-to-identify-time-and-space-complexity-of-recursive-backtracking-algorithms-w
Common Approaches to Backtracking Questionsβ
Every backtracking problem is the template above with three decisions: what's a choice, where the loop starts, and when to prune.
| Pattern | Loop | Record when | Example |
|---|---|---|---|
| Subsets | range(start, n), recurse with i + 1 | Every node | Subsets |
| Combinations | range(start, n), recurse with i + 1 | Path has length k | Combinations |
| Combination sum (reuse allowed) | range(start, n), recurse with i | Remaining target is 0 | Combination Sum |
| Permutations | All of nums, skip used ones | Path has length n | Permutations |
| Input has duplicates | Sort, skip nums[i] == nums[i-1] when i > start | β | Subsets II |
| Constraint placement | One row/cell per level, prune invalid placements early | Board is full | N-Queens, Sudoku Solver |
| Grid search | Four neighbours; mark the cell, recurse, unmark | Word fully matched | Word Search |
| Mistake | Result |
|---|---|
res.append(track) | β Every result is the same list, empty at the end. Append track[:] |
Forgetting track.pop() | β Later branches inherit earlier choices |
if i in track for permutations with duplicates | β Treats equal values as one. Track used indexes instead |
Recursing with start + 1 instead of i + 1 | β Re-picks earlier numbers, so [2, 1] appears next to [1, 2] |
Backtracking vs DPβ
Backtracking enumerates every solution, so it's exponential by design. If the question only wants the count or the best one, and the same (index, remaining) state repeats, memoise it: that's dynamic programming.
| Question | Approach |
|---|---|
| "Return all subsets / combinations / boards" | Backtracking |
| "How many ways", "minimum number" | DP |
| "Is there any way" | Backtracking with early return, or DP if states repeat |
Grid searchβ
Mark the cell before recursing and restore it after, so one path can't reuse a cell but other paths still can.
def exist(board, word):
rows, cols = len(board), len(board[0])
def dfs(r, c, i):
if i == len(word):
return True
if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[i]:
return False
board[r][c] = "#" # mark visited
found = any(dfs(r + dr, c + dc, i + 1) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))
board[r][c] = word[i] # unmark
return found
return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))
Example Solutionsβ
Combinationsβ
Solution: Backtrackingβ
Figure REC-1: Combinations for n = 4, k = 2. Each branch only picks numbers larger than the last one, so [2, 1] is never built. Amber nodes are results: the path reached length k.
def combine(self, n, k):
res = []
self.backtrack(n, k, 1, [], res)
return res
def backtrack(self, n, k, start, track, res):
if len(track) == k:
res.append(track[:]) # copy: track keeps changing after this
return
for i in range(start, n+1): # Order matters, increasing
track.append(i)
self.backtrack(n, k, i + 1, track, res)
track.pop()
Permutationsβ
Solution: Backtrackingβ
Figure REC-2: Permutations of [1, 2, 3]. Each branch picks any number not already on the path, so order matters and every leaf is distinct. Amber nodes are results.
def permute(self, nums):
res = []
self.backtrack(nums, [], res)
return res
def backtrack(self, nums, track, res):
if len(track) == len(nums):
res.append(track[:]) # copy: track keeps changing after this
return
for i in nums: # Order does not matter so we loop through entire array
if i in track: # Exclude numbers already in track
continue
track.append(i)
self.backtrack(nums, track, res)
track.pop()
Subsets IIβ
Solution: Backtrackingβ
def subsetsWithDup(self, nums):
res = []
nums.sort() # Sort so duplicates sit next to each other
self.backtrack(nums, 0, [], res)
return res
def backtrack(self, nums, start, track, res):
res.append(track[:])
for i in range(start, len(nums)):
if i > start and nums[i] == nums[i-1]: # IMPT: Skips over duplicate subsets
continue
track.append(nums[i])
self.backtrack(nums, i + 1, track, res)
track.pop()