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.
- 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.
Why It Matters: Controlled Exponential Search
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
pathlist and snappingpath.copy()only at valid answers instead of creatingpath + [x]lists at every intermediate call. - Early pruning: Sorting candidates and stopping (
breakorcontinue) the moment a partial branch cannot possibly succeed.
Mental Model: The Decision Tree & Universal 3-Step Template
+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:
- Base case / Record: If
pathis a valid answer (or at every node for Subsets), appendpath.copy(). - Choose:
path.append(choice)(and markused[i] = Truefor permutations). - Explore: Recurse deeper (
dfs(i + 1)ordfs(i)if reuse is allowed). - Unchoose:
path.pop()(and unmarkused[i] = False) so the next branch starts with a clean slate!
Step-by-Step Dry-Run Trace: subsets([1, 2])
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 resultTrace every call frame on nums = [1, 2]:
| Call | start | path on Entry | Recorded in result | Loop Actions |
|---|---|---|---|---|
| 1 | 0 | [] | [[]] | i=0: push 1, call backtrack(1) |
| 2 | 1 | [1] | [[], [1]] | i=1: push 2, call backtrack(2) |
| 3 | 2 | [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) |
| 4 | 2 | [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 Type | Next Recursive Index | Duplicate 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 > rem | Exponential in target |
Permutations (n! answers) | Loop 0..n-1 with used array | Sort 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,000frames (sys.getrecursionlimit()). Backtracking trees rarely exceed depth30–50, but deep linear recursion (n = 5,000) requires an iterative loop orsys.setrecursionlimit.
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)).
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:
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
What happens in backtracking if you write res.append(path) instead of res.append(path.copy())?
For an input array of n distinct elements, how many total subsets exist?
In subsets, why do we pass i + 1 (not start + 1) to the recursive call dfs(i + 1)?