3. Recursion, Searching & Sorting

Recursion Trees & Backtracking (Subsets, Permutations & Pruning)

Think recursively without getting lost: identify base cases, draw decision trees, and master Python's choose -> explore -> unchoose backtracking template.

5 min readUpdated 2026-11-30
In This Lesson
  • Trace recursive call stacks and define rock-solid base cases
  • Generate subsets, combinations, and permutations using the choose -> explore -> unchoose template
  • Prune invalid branches early to avoid wasted exponential work

When a problem asks for all valid subsets, combinations, permutations, or board paths (like Word Search, N-Queens, or Sudoku), you are looking at a backtracking problem—systematically exploring a decision tree and undoing each choice when returning.

Unlike linear array problems, enumerating all combinations or permutations genuinely requires exponential output (2ⁿ subsets or n! permutations). The difference between a clean pass and a Time Limit Exceeded (TLE) comes down to:

  • Zero wasted copies: Mutating one shared path list and snapping path.copy() only at valid answers instead of creating path + [x] lists at every intermediate call.
  • Early pruning: Sorting candidates and stopping (break or continue) the moment a partial branch cannot possibly succeed.

Mental Model: The Decision Tree & Universal 3-Step Template

Backtracking Decision Tree: subsets([1, 2])
start: []

+1 → [1]

+2 → [1, 2] (then pop!)

skip 1 → [2]

or skip 2 → []

Every branch follows Choose (append) → Explore (recurse) → Unchoose (pop), creating 2ⁿ subsets via path.copy().

Every backtracking helper dfs(...) follows the exact same Choose → Explore → Unchoose rhythm:

  1. Base case / Record: If path is a valid answer (or at every node for Subsets), append path.copy().
  2. Choose: path.append(choice) (and mark used[i] = True for permutations).
  3. Explore: Recurse deeper (dfs(i + 1) or dfs(i) if reuse is allowed).
  4. Unchoose: path.pop() (and unmark used[i] = False) so the next branch starts with a clean slate!

Step-by-Step Dry-Run Trace: subsets([1, 2])

python
def subsets(nums: list[int]) -> list[list[int]]:
    result: list[list[int]] = []
    path: list[int] = []

    def backtrack(start: int) -> None:
        result.append(path.copy())
        for i in range(start, len(nums)):
            path.append(nums[i])     # Choose
            backtrack(i + 1)         # Explore
            path.pop()               # Unchoose

    backtrack(0)
    return result

Trace every call frame on nums = [1, 2]:

Callstartpath on EntryRecorded in resultLoop Actions
10[][[]]i=0: push 1, call backtrack(1)
21[1][[], [1]]i=1: push 2, call backtrack(2)
32[1, 2][[], [1], [1, 2]]range(2, 2) empty → return, pop 2 (path=[1])
(back in 1)0[] (after pop 1)—i=1: push 2, call backtrack(2)
42[2][[], [1], [1, 2], [2]]range(2, 2) empty → return, pop 2 (path=[])

Total: 4 = 2² subsets ([[], [1], [1, 2], [2]]) with zero duplicate combinations like [2, 1], because backtrack(i + 1) only looks forward!

Subsets vs Combinations vs Permutations

Problem TypeNext Recursive IndexDuplicate Handling (if input has duplicates)Time Complexity
Subsets (2ⁿ answers)dfs(i + 1)Sort first, skip if i > start and nums[i] == nums[i - 1]O(n · 2ⁿ)
Combination Sum (reuse allowed)dfs(i, rem - c)Sort first, break if c > remExponential in target
Permutations (n! answers)Loop 0..n-1 with used arraySort first, skip if i > 0 and nums[i] == nums[i-1] and not used[i-1]O(n · n!)

Edge Cases to Always Check

  • Empty input []: subsets([]) returns [[]]; permutations([]) returns [[]].
  • Single element [7]: subsets([7]) returns [[], [7]].
  • Python recursion limit: Default stack depth is 1,000 frames (sys.getrecursionlimit()). Backtracking trees rarely exceed depth 30–50, but deep linear recursion (n = 5,000) requires an iterative loop or sys.setrecursionlimit.
The #1 Backtracking Bug: Forgetting .copy()

If you write result.append(path) instead of result.append(path.copy()), every entry in result points to the same list object—which gets .pop()-ed back down to [] by the time backtrack(0) finishes! Always append path.copy() (or list(path)).

Avoid Passing Slices Like nums[i + 1:]

Passing start index (dfs(i + 1)) costs O(1) per call, whereas slicing nums[i + 1:] allocates a brand-new list copy on every node of the recursion tree.

Try It Yourself in the Playground

Run Subsets, Combination Sum (with early pruning), and Permutations live below:

Python 3Try It Live: Backtracking Subsets, Combinations & Permutations
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Why did combination_sum sort candidates first and break when candidates[i] > remaining?

Quick Checkpoints

Check Your Understanding

What happens in backtracking if you write res.append(path) instead of res.append(path.copy())?

Check Your Understanding

For an input array of n distinct elements, how many total subsets exist?

Check Your Understanding

In subsets, why do we pass i + 1 (not start + 1) to the recursive call dfs(i + 1)?