Backtracking: subsets and permutations
About this lesson
Some problems have no clever shortcut: you have to try every option. Backtracking does that in an orderly way. It draws the options as a tree of choices and walks it depth first with one shared list, using three moves: choose, explore, un-choose. Watch it list all 8 subsets and all 6 orders of [1, 2, 3], then count what the search costs. The Software lessons "Recursion" and "Dynamic programming" cover the recursive calls and the reuse of answers that this lesson builds on.
A tree of choices
Goal: list every subset of [1, 2, 3]. Each number is one yes-or-no choice: take it (left edge) or skip it (right edge). Three choices make 2 × 2 × 2 = 8 leaves, one per subset. Each block shows the list chosen so far.
nums = [1, 2, 3] level 0: decide 1 level 1: decide 2 level 2: decide 3 left edge = take right edge = skip leaves: 2 × 2 × 2 = 8 [1, 2, 3] [1, 2] [1, 3] [1] [2, 3] [2] [3] []
Read the lesson step by step
A tree of choices
Goal: list every subset of [1, 2, 3]. Each number is one yes-or-no choice: take it (left edge) or skip it (right edge). Three choices make 2 × 2 × 2 = 8 leaves, one per subset. Each block shows the list chosen so far.
nums = [1, 2, 3] level 0: decide 1 level 1: decide 2 level 2: decide 3 left edge = take right edge = skip leaves: 2 × 2 × 2 = 8 [1, 2, 3] [1, 2] [1, 3] [1] [2, 3] [2] [3] []One shared list: path
The code walks this tree by recursion. Each call is one block, and the rose puck marks the call running now. One shared list, path, holds the choices made so far. Going down an edge changes path; coming back up must undo it.
1 def subsets(nums, i, path, out): 2 if i == len(nums): 3 out.append(path.copy()) 4 return 5 path.append(nums[i]) # choose 6 subsets(nums, i + 1, path, out) # take 7 path.pop() # un-choose 8 subsets(nums, i + 1, path, out) # skip out = [] subsets([1, 2, 3], 0, [], out) print(out) one call = one block of the tree path = the choices on the way from the root to that blockChoose and explore
Line 5 chooses: path.append(1) puts 1 in path. Line 6 explores: one call further down. The same happens for 2 and 3. Now i equals len(nums), so every number is decided and line 3 saves a copy: [1, 2, 3] is found.
subsets(i=0) line 5 path.append(1) path = [1] line 6 call i=1 subsets(i=1) line 5 path.append(2) path = [1, 2] line 6 call i=2 subsets(i=2) line 5 path.append(3) path = [1, 2, 3] line 6 call i=3 subsets(i=3) line 2 3 == len(nums) line 3 out.append(path.copy()) out = [[1, 2, 3]]Un-choose, then skip
The leaf returns to the call for 3. Line 7 un-chooses: path.pop() removes 3, so path is [1, 2] again. Line 8 explores the skip branch with that same list and saves [1, 2]. Undoing each choice lets one list serve every branch.
subsets(i=3) line 4 return subsets(i=2) line 7 path.pop() path = [1, 2] line 8 call i=3 (skip 3) subsets(i=3) line 3 out.append(path.copy()) out = [[1, 2, 3], [1, 2]] copy, not path itself: path keeps changing, a saved copy does notThe whole walk
Run it to the end. The puck goes depth first: the take edge, back up, then the skip edge. It saves 8 subsets, [1,2,3], [1,2], [1,3], [1], [2,3], [2], [3], [], in 15 calls, with one three-cell list the whole time.
calls: 15 (1 + 2 + 4 + 8) found: 8 order: 1. [1, 2, 3] 2. [1, 2] 3. [1, 3] 4. [1] 5. [2, 3] 6. [2] 7. [3] 8. [] take is tried before skip, so [1, 2, 3] comes first and [] lastCost: 2ⁿ leaves
Each extra number doubles the leaves: n numbers give 2ⁿ subsets and 2ⁿ⁺¹ − 1 calls (15 here). Copying a leaf costs up to n steps, so the search is Θ(n·2ⁿ). For n = 20 that is 1,048,576 subsets.
n subsets 2ⁿ calls 2ⁿ⁺¹ − 1 1 2 3 2 4 7 3 8 15 4 16 31 10 1024 2047 20 1048576 2097151 items copied into out: n·2ⁿ⁻¹ (each number is in half the subsets) n = 3: 12 items total work Θ(n·2ⁿ)Permutations: order matters
Now list every order of [1, 2, 3]. At each level, choose any number not yet in path. The root has 3 choices, then 2, then 1: 3 × 2 × 1 = 6 leaves. The pattern is the same: append, recurse, pop.
1 def perms(nums, path, out): 2 if len(path) == len(nums): 3 out.append(path.copy()) 4 return 5 for x in nums: 6 if x not in path: 7 path.append(x) # choose 8 perms(nums, path, out) # explore 9 path.pop() # un-choose out = [] perms([1, 2, 3], [], out) print(out) leaves: 3 × 2 × 1 = 3! = 6Walk the order tree
Line 5 tries each number; line 6 skips any already in path. Each choice is appended, explored, then popped so the next number can take its place. Found: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1], in 16 calls.
calls: 16 (1 + 3 + 6 + 6) found: 6 order: 1. [1, 2, 3] 2. [1, 3, 2] 3. [2, 1, 3] 4. [2, 3, 1] 5. [3, 1, 2] 6. [3, 2, 1] same order as itertools.permutations([1, 2, 3])Cost: n! leaves
n numbers have n! orders: 3! = 6, but 10! = 3,628,800. Backtracking cannot shrink a list that long; it saves rebuilding path at every leaf. It shines when a rule can stop a branch early, the subject of N-queens and pruning.
n n! 1 1 2 2 3 6 4 24 5 120 10 3,628,800 12 479,001,600 calls = 1 + n + n(n−1) + … + n! (16 for n = 3) at least n! calls: one per leaf
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01How many subsets does a list of 5 different numbers have, counting [] and the full list?
Each number is one take-or-skip choice, so 5 numbers give 2 × 2 × 2 × 2 × 2 = 2⁵ = 32 leaves in the choice tree, one per subset. 120 is 5!, the number of orders.
02In subsets, what goes wrong if line 3 is out.append(path) instead of out.append(path.copy())?
There is only one path list. Appending it stores a reference, not a snapshot, and every pop changes it. When the search ends path is [], so every entry shows []. path.copy() saves a snapshot that later pops cannot touch.
03Why does each path.append in the code have a matching path.pop() after the recursive call?
This is the un-choose step. The skip branch (or the next number in the loop) must start from the same path as the branch before it. Undoing the choice is what lets one list serve every branch of the tree.
04The subsets search on [1, 2, 3] makes 15 calls. How many calls does it make on a list of 4 numbers?
The choice tree is a full binary tree with n + 1 levels: 1 + 2 + 4 + 8 + 16 = 31 = 2⁵ − 1 calls. 16 of them are leaves, one per subset.
05Which statement about backtracking for permutations of n distinct numbers is true?
Every order is a leaf, and there are n! of them (10! = 3,628,800). No two calls share a subproblem, so there is nothing to reuse. Backtracking pays off when a rule can cut a branch before it reaches the leaves.
Glossary
- Backtracking
- A way to try every option: build a solution one choice at a time, and undo the last choice to try the next one when a branch is finished.
- Choice tree
- A tree where each node is a partial solution and each edge is one choice. The leaves are complete solutions. Also called a state-space tree.
- Choose, explore, un-choose
- The three moves of backtracking: change the shared state, recurse, then put the state back exactly as it was.
- Depth first
- Going as deep as possible down one branch before coming back up to try the next one. Recursion does this naturally.
- Subset
- Any selection of items from a set, in no particular order, including none and all of them. An n-item set has 2ⁿ subsets.
- Permutation
- An ordering of all the items. n different items have n! = n × (n − 1) × … × 1 permutations.
- Shallow copy
- A new list holding the same items as the old one. Changing the old list afterwards does not change the copy. list.copy() makes one.
- Pruning
- Stopping a branch early because no leaf below it can be a valid answer. It is what makes backtracking faster than plain brute force.
Notes and sources
- Choose, explore, un-choose is the shape of every backtracking search: change the shared state, recurse, then put the state back exactly as it was. Stanford CS106B teaches it under that name; Sedgewick and Wayne call the last step "clean up".
- out.append(path.copy()) saves a copy. Writing out.append(path) would store the same list object 8 times, and since path ends empty, out would hold 8 empty lists.
- x not in path checks the list item by item, up to n steps. A list of n True/False flags (used[x]) makes the check one step; the tree and the output stay the same. It also assumes the numbers are distinct.
- Unlike dynamic programming, there is nothing to reuse here: every call has a different path, so no two calls solve the same subproblem. MIT 6.006 calls a recursion dynamic programming when its graph of calls overlaps (a DAG); here the graph of calls is a tree with no overlap.
- In real code itertools.permutations and itertools.combinations do this for you, in the same order. Writing the search yourself matters when you add rules that cut branches.
- Sedgewick and Wayne, Algorithms 4th ed., lecture slides: Combinatorial Search (backtracking, 2ᴺ bit strings, N! permutations)
- Sedgewick and Wayne, Computer Science §2.3: Recursion (permutations and combinations)
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 15: Recursive Algorithms
- Stanford CS106B, Lecture 11: Recursive Backtracking and Enumeration
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), Appendix C.1: Counting
- Python Tutorial: More on Lists (append, pop, copy)
- Python Library: itertools.permutations and itertools.combinations
Quiz Unlocks after the last step.