Integer partitions
Count the ways to write n as a sum of positive integers (order does not matter), by dynamic programming that allows one part size at a time.
A partition of n writes it as a sum of positive integers, ignoring the order: 4 = 3 + 1 = 2 + 2 = 2 + 1 + 1 = 1 + 1 + 1 + 1 (five partitions).
- Time:
O(n²) - Space:
O(n) - Grimaldi, chapter 9
- Horowitz–Sahni, chapter 5
p(5) = 7: 5, 4+1, 3+2, 3+1+1, 2+2+1, 2+1+1+1 and 1+1+1+1+1.
def partitions(n):# ways[t] = the number of ways to write t as a sum of the parts allowed so far.ways = [1] + [0] * nrows = []for part in range(1, n + 1):for total in range(part, n + 1):ways[total] = ways[total] + ways[total - part]rows.append([part] + ways)return ways[n]
Start
The table is still empty.
Local variables
Orange = changed in this step
Call stack
- partitions()line 1
Explanation
The idea
A partition of n writes it as a sum of positive integers, ignoring the order: 4 = 3 + 1 = 2 + 2 = 2 + 1 + 1 = 1 + 1 + 1 + 1 (five partitions).
Dynamic programming
Allow the parts one size at a time. When part part is added, each partition of total either does not use part
(the old answer), or uses it at least once (so removing one leaves a partition of total − part):
ways[total] ← ways[total] + ways[total − part]
Because the inner loop goes upward, ways[total − part] already includes part; so a part can be used many times.
This is the same pattern as the coin change problem.
What to watch in the trace
- Each table row is the whole
waysarray after one more part is allowed; the last filled column is the answer at that stage.