Backtracking

1 / 11

What is Backtracking?

Recursion with choice and undo

  1. Make a choice
  2. Recursively explore
  3. Undo the choice (backtrack)

DFS on an implicit decision tree

2 / 11

The Template

def backtrack(path, choices):
    if is_complete(path):
        result.append(path[:])  # Copy!
        return

    for choice in choices:
        if not is_valid(choice):
            continue  # Prune

        path.append(choice)      # Choose
        backtrack(path, ...)     # Explore
        path.pop()               # Unchoose
3 / 11

Subsets Pattern

Include or exclude each element

def backtrack(start, path):
    result.append(path[:])  # Every path is valid

    for i in range(start, len(nums)):
        path.append(nums[i])
        backtrack(i + 1, path)  # i+1 avoids duplicates
        path.pop()

2^n subsets total

4 / 11

Permutations Pattern

Use any unused element

def backtrack(path):
    if len(path) == n:
        result.append(path[:])
        return

    for i in range(n):
        if used[i]:
            continue
        used[i] = True
        path.append(nums[i])
        backtrack(path)
        path.pop()
        used[i] = False

n! permutations total

5 / 11

N-Queens Constraint Tracking

Track attacked positions:

  • cols[col] — column occupied
  • diag1[row-col] — main diagonal
  • diag2[row+col] — anti-diagonal
if cols[col] or diag1[d1] or diag2[d2]:
    continue  # Prune
6 / 11

Subsets vs Permutations

Subsets Permutations
Order doesn't matter Order matters
Any size (0 to n) Fixed size (n)
Use start index Use used array
2^n results n! results
7 / 11

Key Insight: Copy the Path!

Wrong:

result.append(path)  # References same list

Correct:

result.append(path[:])  # Creates copy
8 / 11

Complexity

Problem Solutions Time
Subsets 2^n O(n * 2^n)
Permutations n! O(n * n!)
N-Queens varies O(n!)
9 / 11

Common Mistakes

  1. Forgetting to copy the path
  2. Not undoing all state changes
  3. Wrong index bounds (duplicates)
  4. Pruning too late
10 / 11

When to Use Backtracking

  • Generate ALL solutions
  • Solutions build incrementally
  • Can prune invalid paths early
  • Exponential but manageable search space
11 / 11
←/→ or click edges to navigate · ? help · N notes · F fullscreen