Skip to content

Backtracking

Backtracking in under a minute

Backtracking is a depth-first walk over a decision tree. At each node you pick one option, go deeper, then take the pick back and try the next option. It is brute force made tidy: you visit every candidate once, and you can cut off a branch the moment it cannot work.

  • The problem says “return all” subsets, combinations, permutations, or paths.
  • You build the answer step by step, and each step has a few options.
  • The input is small (n up to about 10 to 20). That hints at exponential time.
  • You need to search a grid or graph for a path without reusing cells.
  • A partial answer can be rejected early (sum too big, wrong letter).
def solve(nums):
res, path = [], []
def backtrack(start):
if is_complete(path): # 1. record a finished answer
res.append(path[:]) # copy! path keeps changing
return
for i in range(start, len(nums)):
if not valid(nums[i]): # 2. prune dead branches early
continue
path.append(nums[i]) # 3. choose
backtrack(i + 1) # 4. explore
path.pop() # 5. un-choose (exact undo of step 3)
backtrack(0)
return res

Only two things change between problems: what you pass on, and when you record.

Problem type Next call Record when
Subsets backtrack(i + 1) at every node
Combinations backtrack(i + 1), or i if reuse is allowed path hits the goal
Permutations backtrack(), loop from 0 and skip used path has length n
Grid path backtrack(r, c, k) over 4 neighbours k == len(word)

The start index only looks right, so [1, 2] and [2, 1] are never both built. Permutations want order to matter, so they scan everything and track what is used.

  • Subsets — record every path while choosing or skipping each number
  • Combination Sum — reuse numbers; the start index blocks duplicates
  • Permutations — a used-array lets every order appear once
  • Word Search — grid DFS that marks cells and restores them