Skip to main content

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).

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.

PatternLoopRecord whenExample
Subsetsrange(start, n), recurse with i + 1Every nodeSubsets
Combinationsrange(start, n), recurse with i + 1Path has length kCombinations
Combination sum (reuse allowed)range(start, n), recurse with iRemaining target is 0Combination Sum
PermutationsAll of nums, skip used onesPath has length nPermutations
Input has duplicatesSort, skip nums[i] == nums[i-1] when i > startβ€”Subsets II
Constraint placementOne row/cell per level, prune invalid placements earlyBoard is fullN-Queens, Sudoku Solver
Grid searchFour neighbours; mark the cell, recurse, unmarkWord fully matchedWord Search
MistakeResult
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.

QuestionApproach
"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

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​

1234234344[1, 2][1, 3][1, 4][2, 3][2, 4][3, 4][1][2][3][4][ ]

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​

123231312323121[1, 2, 3][1, 3, 2][2, 1, 3][2, 3, 1][3, 1, 2][3, 2, 1][1, 2][1, 3][2, 1][2, 3][3, 1][3, 2][1][2][3][ ]

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()