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 it

How many subsets are produced?

Count: subsets output.

Measured counts

110100100010k1.0e+2k1.0M5101520ncount (log scale)
Measured
Table
ncount
416
664
8256
101,024
124,096
1416,384
1665,536
18262,144
201,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ⁿ
  1. Each element is either in or out: 2 choices, n times: 2ⁿ subsets.
  2. Building each subset copies up to n elements, so the total time is Θ(n · 2ⁿ).
  3. 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).