Sub topic 5
Generating All Subsets
This chapter assumes you know the choose, explore, unchoose template and why results must be copied before they are stored. It also assumes you can read Big-O notation. The task here is to produce every subset of a list of distinct values. For [1, 2, 3] that means all eight subsets, from the empty set up to the full list.
Modeling the Search
Each node in the state-space tree is a partial subset. The trick that avoids duplicates is a start index. When a node picks nums[i], its children may only pick elements after position i. So the tree can produce [1, 3] but never [3, 1], and each subset appears on exactly one path.
Every node in this tree is a valid answer, and that includes the root. Many backtracking problems record a result only at the leaves. Subsets are different: you record at every node, before the loop runs.
The 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]]Here is what each line does:
result.append(path[:])records the current node. It stores a copy becausepathkeeps changing after this line.range(start, len(nums))offers only elements that come later in the list. This loop is the "choose" step.backtrack(i + 1)explores. The argument isi + 1, notstart + 1, because the next pick must come after the element just chosen.path.pop()unchooses, so the next loop iteration starts from the same partial subset.
There is no explicit base case. Once start == len(nums), the loop body never runs and the call returns by itself.
Common Mistakes
| Mistake | Symptom |
|---|---|
| `result.append(path)` without copying | Every entry ends up as `[]`, because they all point to the same list |
| `backtrack(start + 1)` instead of `backtrack(i + 1)` | You get repeated subsets such as `[2, 2]`, or subsets in the wrong order |
| Recording only when `start == len(nums)` | You get only the leaves, so subsets are missing |
| Forgetting `path.pop()` | Elements pile up and results grow without limit |
Cost
A list of n distinct elements has 2^n subsets. Each copy can take up to O(n) time, so the total running time is O(n · 2^n). The recursion depth and path use O(n) extra space, not counting the output. A later chapter covers how to analyze this kind of cost in general.
Exercise
Change subsets so that it returns only the subsets of exactly size k. For example, with nums = [1, 2, 3, 4] and k = 2 it should return the 6 pairs. Where does the result get recorded, and how can you stop early?
Show answer
Record only when len(path) == k, and return right after recording, because nothing deeper can have size k. To prune, loop only while enough elements remain: for i in range(start, len(nums) - (k - len(path)) + 1). Without this, branches that can never reach size k are still explored.
Exercise
How many times is backtrack called for an input of 4 distinct elements, and why?
Show answer
16 times. Each call records exactly one subset, and there are 2^4 = 16 subsets.