Sub topic 5
Generating All Subsets
This chapter assumes you can read Python functions and loops, follow a recursive call with a base case, and use Big-O notation. It also builds on the choose-explore-unchoose template and the rule about copying results with path[:] from the previous chapters.
Generating every subset of a list is the simplest complete backtracking problem. A set of n elements has 2^n subsets, and the algorithm must produce each one exactly once. The problem has no constraints and no early exits, so it shows the template on its own before later chapters add pruning.
The Problem
Given a list of distinct values such as [1, 2, 3], return every subset, including the empty subset and the full list. Order inside a subset does not matter, so [1, 2] and [2, 1] are the same subset and only one of them should appear.
That last requirement shapes the whole design. A naive search that adds "any unused element" at each step would build [1, 2] and [2, 1] as separate paths. To avoid this, the search needs a rule that gives each subset exactly one way to be built.
Two Ways to Shape the Tree
There are two standard state-space trees for subsets. Both are correct, and the difference between them is worth understanding.
| Formulation | Decision at each node | Where results are recorded | Tree shape |
|---|---|---|---|
| Include/exclude | Take or skip `nums[i]` | Only at leaves (depth `n`) | Full binary tree, `2^n` leaves |
| Start index | Pick the next element from `nums[start:]` | At every node | `2^n` nodes total, one per subset |
The include/exclude tree
In the include/exclude tree, each level makes a yes-or-no decision about one element. After n decisions you reach a leaf, and the leaf is a subset. Each subset corresponds to exactly one sequence of yes/no answers, so nothing is duplicated.
def subsets_binary(nums):
result = []
path = []
def backtrack(i):
if i == len(nums):
result.append(path[:])
return
# Choice 1: include nums[i]
path.append(nums[i])
backtrack(i + 1)
path.pop()
# Choice 2: exclude nums[i]
backtrack(i + 1)
backtrack(0)
return result
print(subsets_binary([1, 2, 3]))
# [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]This version makes 2^(n+1) - 1 calls, and only the 2^n leaf calls record anything. It maps directly onto the bitmask view: each subset is an n-bit number.
The start-index tree
In the start-index tree, every node already is a subset. Its children extend it with one element that appears later in the input than anything already chosen. Because elements are always added in increasing index order, [2, 1] can never be built. The only route to the subset {1, 2} is "pick index 0, then pick index 1".
The tree has exactly eight nodes for eight subsets, so no call is wasted. This is the formulation used in most of the rest of the tutorial, because it extends naturally to combinations, target sums, and duplicate skipping.
The Start-Index Implementation
def subsets(nums):
result = []
path = []
def backtrack(start):
result.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return result
print(subsets([1, 2, 3]))
# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]Map each line to the template:
- Record:
result.append(path[:])runs at the top of every call, because every node is a valid answer. The function has no explicit base case. Whenstart == len(nums)the loop runs zero times and the call returns on its own. - Choose:
path.append(nums[i])adds one later element. - Explore:
backtrack(i + 1)allows only elements after indexifrom here on. - Unchoose:
path.pop()restorespathbefore the loop tries the nexti.
Tracing the calls
Following the call order explains the output order. The search is depth-first, so it goes as deep as possible along 1 before it ever considers starting with 2.
| Step | Call | `path` on entry | Recorded | Loop tries |
|---|---|---|---|---|
| 1 | `backtrack(0)` | `[]` | `[]` | i = 0, 1, 2 |
| 2 | `backtrack(1)` | `[1]` | `[1]` | i = 1, 2 |
| 3 | `backtrack(2)` | `[1, 2]` | `[1, 2]` | i = 2 |
| 4 | `backtrack(3)` | `[1, 2, 3]` | `[1, 2, 3]` | none |
| 5 | `backtrack(3)` | `[1, 3]` | `[1, 3]` | none |
| 6 | `backtrack(2)` | `[2]` | `[2]` | i = 2 |
| 7 | `backtrack(3)` | `[2, 3]` | `[2, 3]` | none |
| 8 | `backtrack(3)` | `[3]` | `[3]` | none |
Between steps 4 and 5, two pops happen: 3 is popped when step 4 returns, and 2 is popped when step 3 returns. Then the loop in step 2 moves on to i = 2. At any moment, path holds exactly the choices on the route from the root to the current node.
Common Errors
These three bugs account for most broken subset generators. Each one has an output you can recognize.
| Bug | Code | Symptom for `[1, 2, 3]` |
|---|---|---|
| Storing a reference | `result.append(path)` | Eight empty lists: `[[], [], [], [], [], [], [], []]` |
| Wrong recursion index | `backtrack(start + 1)` | Subsets that reuse an element, such as `[1, 3, 3]` |
| Missing unchoose | no `path.pop()` | `path` keeps growing, so recorded lists get longer and are wrong |
The first bug happens because every entry in result points to the same list object. All the pops at the end of the search empty that list. The previous chapter covers this in detail.
The second bug is subtle. With start + 1, the child's range depends on where the parent's loop began, not on which element was just chosen. When the loop in backtrack(1) picks index 2, it calls backtrack(2), which can pick index 2 again. Recursing on i + 1 is what ties "only later elements" to the element just chosen.
An Iterative Cross-Check
When you test a backtracking generator, compare it against an independent method. A bitmask loop makes a good reference: bit j of mask decides whether nums[j] is included.
def subsets_bitmask(nums):
n = len(nums)
return [[nums[j] for j in range(n) if mask >> j & 1]
for mask in range(1 << n)]
def same_subsets(a, b):
return sorted(map(sorted, a)) == sorted(map(sorted, b))
def subsets(nums):
result, path = [], []
def backtrack(start):
result.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return result
for data in ([], [5], [1, 2, 3], list(range(6))):
assert same_subsets(subsets(data), subsets_bitmask(data))
assert len(subsets(data)) == 2 ** len(data)
print("all checks passed")The bitmask version is shorter, but it cannot skip branches. Backtracking matters once constraints let you abandon a partial subset early, for example "subsets whose sum is at most 10". The start-index tree lets you cut off a whole subtree with one check. The bitmask loop still visits all 2^n masks.
Cost in Brief
The start-index version makes exactly 2^n calls, one per subset. Copying a path costs up to n, so total time is O(n · 2^n). That is optimal, because the output itself has that size. Extra space beyond the output is O(n), for the recursion depth plus path. A later chapter on complexity analysis shows how to count nodes for trees whose shape is less regular.
Edge Cases
- Empty input:
subsets([])returns[[]]. The empty set has one subset, and the firstappendrecords it before the loop runs zero times. - Large
n: Recursion depth is onlyn + 1, so Python's default recursion limit is not the problem. Output size is:n = 25already produces more than 33 million lists. - Repeated values: For
[1, 2, 2]this code produces[1, 2]twice, because the two2s sit at different indices. Fixing that needs a sort plus a skip rule, covered in "Avoiding Duplicate Results". - Non-list iterables: The code indexes
nums, so convert sets or generators withlist(...)first.
Exercise
Modify the start-index subsets function so it returns only subsets of exactly size k (the combinations of nums choose k). Where should the recording happen, and what extra check can stop the search from exploring branches that are too short to ever reach size k?
Show answer
Record only when len(path) == k, and return immediately afterwards, since no larger subset is wanted. For pruning, loop over i in range(start, len(nums) - (k - len(path)) + 1). If fewer than k - len(path) elements remain after index i, the branch can never reach size k. For nums = [1, 2, 3, 4] and k = 2, the result is [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]].
Exercise
How many times is backtrack called when the start-index subsets runs on a 4-element list, and how many when subsets_binary runs on the same list? Explain the difference.
Show answer
The start-index version makes 16 calls, because each call corresponds to exactly one node and every node is one of the 2^4 = 16 subsets. The include/exclude version makes 2^5 - 1 = 31 calls, because it builds a full binary tree of depth 4: 16 leaves that record subsets plus 15 internal decision nodes that record nothing.
Exercise
A colleague writes backtrack(start + 1) instead of backtrack(i + 1). Give one subset of [1, 2, 3] that the buggy version outputs and the correct version does not, and explain why it appears.
Show answer
[1, 3, 3] is one example. From [1], the call backtrack(1) picks index 2 and then calls backtrack(2) instead of backtrack(3). That call's loop starts at index 2 again, so it appends 3 a second time. The child's range should depend on the index just chosen, not on where the parent's loop started.