Notes
All notes

Recursion and Backtracking (DSA #23)

Some problems are defined in terms of themselves. A file system is folders that contain folders; a sorted list is a pivot with two smaller sorted lists around it; “all subsets” is “include this element or not” applied to the rest. Recursion is how you write those definitions directly, and backtracking is recursion with a disciplined undo, used to systematically explore a space of choices — permutations, combinations, puzzles, and constraint problems.

This chapter covers the shape of a recursive function, the backtracking template, and the four classic problems: subsets, permutations, combinations, and N-Queens.

The shape of recursion

Every recursive function has two parts:

def factorial(n):
    if n <= 1:                # base case
        return 1
    return n * factorial(n - 1)   # recursive case

Two things to reason about: that each call makes progress toward the base case (so it terminates), and that the base case answer, combined with the recursive result, is correct. The call stack holds one frame per pending call, so recursion uses \(O(\text{depth})\) space (Chapter 1).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, rounded corners=2pt, minimum width=1.6cm, minimum height=0.55cm, font=\small\ttfamily},
  a/.style={->, thick}]
  \node[n, fill=blue!10] (a) at (0,0) {fact(4)};
  \node[n, fill=blue!10] (b) at (0,-0.8) {4 * fact(3)};
  \node[n, fill=blue!10] (c) at (0,-1.6) {3 * fact(2)};
  \node[n, fill=green!18] (d) at (0,-2.4) {fact(1) = 1};
  \draw[a] (a) -- (b); \draw[a] (b) -- (c); \draw[a] (c) -- (d);
  \node[font=\rmfamily\small, text=black!60, anchor=west] at (2.2,-1.2) {each call waits for the one below};
\end{tikzpicture}

A recursion tree makes the cost visible. When a call branches into two smaller calls, the tree can grow exponentially — which is exactly the space backtracking searches.

Backtracking: choose, explore, un-choose

Backtracking walks a decision tree. At each step you make a choice, recurse, and then undo the choice so the next branch starts clean.

backtrack(state):
    if state is complete:
        record solution
        return
    for each choice:
        if choice is valid:
            apply(choice)
            backtrack(state)
            undo(choice)      # restore before the next choice

The undo is what distinguishes backtracking from plain recursion: the state is a single mutable structure (a partial list, a board), shared across the tree, and must be restored on the way back up.

Subsets (the power set)

Every element is either in the subset or not — a binary decision tree with \(2^n\) leaves.

def subsets(nums):
    result, path = [], []
    def backtrack(i):
        if i == len(nums):
            result.append(path[:])       # snapshot the current subset
            return
        backtrack(i + 1)                 # choice 1: exclude nums[i]
        path.append(nums[i])
        backtrack(i + 1)                 # choice 2: include nums[i]
        path.pop()                       # undo
    backtrack(0)
    return result

For [1, 2, 3] this produces all eight subsets. The path[:] copy is essential — appending the live list would record later mutations.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, rounded corners=2pt, minimum width=1.0cm, minimum height=0.5cm, font=\small\ttfamily, inner sep=3pt},
  a/.style={->, thick}]
  \node[n, fill=orange!22] (r) at (0,0) {\{\}};
  \node[n, fill=blue!10] (l) at (-2.0,-0.9) {\{\}};
  \node[n, fill=blue!10] (rr) at (2.0,-0.9) {\{1\}};
  \node[n] (ll) at (-2.8,-1.8) {\{\}};
  \node[n] (lr) at (-1.2,-1.8) {\{2\}};
  \node[n] (rl) at (1.2,-1.8) {\{1\}};
  \node[n] (rrr) at (2.8,-1.8) {\{1,2\}};
  \draw[a] (r) -- (l); \draw[a] (r) -- (rr);
  \draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
  \draw[a] (rr) -- (rl); \draw[a] (rr) -- (rrr);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.3) {exclude or include each element: $2^n$ leaves};
\end{tikzpicture}

Permutations

Here the choice is “which element goes next”, and you must skip elements already used. Swapping in place avoids a separate used array.

def permutations(nums):
    result = []
    def backtrack(start):
        if start == len(nums):
            result.append(nums[:])
            return
        for i in range(start, len(nums)):
            nums[start], nums[i] = nums[i], nums[start]   # choose
            backtrack(start + 1)                          # explore
            nums[start], nums[i] = nums[i], nums[start]   # un-choose
    backtrack(0)
    return result

There are \(n!\) permutations, so the search is inherently factorial — the best you can do is prune.

Combinations and pruning

When only combinations of size \(k\) are wanted, stop early when the remaining elements cannot fill \(k\) — a pruned branch.

def combinations(n, k):
    result, path = [], []
    def backtrack(start):
        if len(path) == k:
            result.append(path[:]); return
        remaining, needed = n - start + 1, k - len(path)
        for i in range(start, n + 1):
            if remaining < needed:       # not enough left -> prune
                break
            path.append(i)
            backtrack(i + 1)
            path.pop()
            remaining -= 1
    backtrack(1)
    return result

Pruning is the practical heart of backtracking: reject partial states that cannot lead to a solution before exploring their subtrees.

N-Queens

Place \(n\) queens on an \(n \times n\) board so none attack each other. Backtrack row by row, tracking occupied columns and both diagonals.

def solve_n_queens(n):
    solutions = []
    cols, diag1, diag2 = set(), set(), set()
    board = []
    def backtrack(r):
        if r == n:
            solutions.append(board[:]); return
        for c in range(n):
            if c in cols or (r - c) in diag1 or (r + c) in diag2:
                continue                 # attack -> prune this branch
            cols.add(c); diag1.add(r - c); diag2.add(r + c)
            board.append(c)
            backtrack(r + 1)
            board.pop()
            cols.remove(c); diag1.remove(r - c); diag2.remove(r + c)  # undo
    backtrack(0)
    return solutions

The diagonal trick is the key insight: cells on the same \ diagonal share \(r - c\), and on the same / diagonal share \(r + c\). Checking three sets makes validity \(O(1)\).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  a/.style={->, thick}]
  \draw[step=0.6, thick, black!40] (0,0) grid (2.4,2.4);
  \node[font=\bfseries] at (0.3,2.1) {Q};
  \node[font=\bfseries] at (0.9,0.9) {Q};
  \node[fill=red!12] (0.9,2.1) rectangle (1.5,2.4);
  \node[font=\scriptsize, text=red!70!black] at (1.2,1.2) {x};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.2,-0.2) {attacked squares are pruned before recursing};
\end{tikzpicture}

Pitfalls

QQuestionSelf-check

What are the two essential parts of a recursive function? What is the undo step for in backtracking?

ASolution

A base case answered directly and a recursive case that reduces the input toward the base. The undo restores shared state after exploring one branch, so the next choice starts from a clean partial solution rather than inheriting the previous branch’s mutations.

Next: Divide and Conquer (DSA #24) — split the problem, solve the halves, combine.