Exercise 19 of 30 · intermediate · recursion · exponential · backtracking
Generating every subset
The code
def subsets(items, i=0, chosen=[]):
if i == len(items):
output(chosen)
return
subsets(items, i + 1, chosen) # skip items[i]
subsets(items, i + 1, chosen + [items[i]]) # take itHow many subsets are produced?
Count: subsets output.
Measured counts
Table
| n | count |
|---|---|
| 4 | 16 |
| 6 | 64 |
| 8 | 256 |
| 10 | 1,024 |
| 12 | 4,096 |
| 14 | 16,384 |
| 16 | 65,536 |
| 18 | 262,144 |
| 20 | 1,048,576 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n · 2ⁿ) including copying; 2ⁿ outputs
- Extra space
- Θ(n) besides the output
- Exact count
- 2ⁿ
- Each element is either in or out: 2 choices, n times: 2ⁿ subsets.
- Building each subset copies up to n elements, so the total time is Θ(n · 2ⁿ).
- No algorithm can list 2ⁿ subsets faster than Ω(2ⁿ): the output itself is that large.
Common mistake: Hoping to optimise an algorithm whose output is exponential. The output size is a lower bound.
Check: measured count ÷ (2ⁿ) settles near 1.00 for large n (growth factors are compared for exponential classes).