"""
Generate all ways to write a positive integer n
as a sum of positive integers (integer partitions).
Example for n = 5:
[
[5],
[4, 1],
[3, 2],
[3, 1, 1],
[2, 2, 1],
[2, 1, 1, 1],
[1, 1, 1, 1, 1]
]
"""
def partitions(n):
"""
Return all partitions of a positive integer n.
Each partition is a list of integers in non-increasing order.
"""
results = []
def backtrack(remaining, max_value, current):
# If nothing remains, we found a valid partition
if remaining == 0:
results.append(current.copy())
return
# Try next numbers from max_value down to 1
for next_value in range(min(remaining, max_value), 0, -1):
current.append(next_value) # choose
backtrack(remaining - next_value, next_value, current) # explore
current.pop() # un-choose (backtrack)
backtrack(n, n, [])
return results
# Run the program:
result = partitions(5)
print(result)
"""
run:
[[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]
"""