Exercise 20 of 30 · intermediate · recursion · factorial · backtracking
Generating every permutation
The code
def permute(items, i=0):
if i == len(items):
output(items)
return
for j in range(i, len(items)):
items[i], items[j] = items[j], items[i]
permute(items, i + 1)
items[i], items[j] = items[j], items[i]How many orderings of n distinct items are there?
Count: permutations output.
Measured counts
Table
| n | count |
|---|---|
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
| 6 | 720 |
| 7 | 5,040 |
| 8 | 40,320 |
| 9 | 362,880 |
| 10 | 3,628,800 |
| 11 | 39,916,800 |
Try to name the class from the shape before opening the answer.
Show the answer and derivation
- Time
- Θ(n · n!) with output
- Extra space
- Θ(n) stack
- Exact count
- n!
- n choices for position 0, n − 1 for position 1, …: n! permutations.
- n! outgrows 2ⁿ quickly: 10! = 3,628,800, 20! ≈ 2.4 × 10¹⁸.
- This is why "try every order" fails beyond about n = 11 on a typical machine.
Common mistake: Treating n! as roughly 2ⁿ. By n = 20, n! is about 2 × 10¹² times larger than 2ⁿ.
Check: measured count ÷ (n!) settles near 1.00 for large n (growth factors are compared for exponential classes).