# Generate all ways to write n as a sum of positive integers.
# Each partition is non‑decreasing (e.g., [1,2,2] instead of [2,1,2]).
def partitions(n)
result = [] # stores all completed partitions
current = [] # current partial partition being built
# Recursive helper:
# remaining — how much is left to reach n
# start — the minimum next value allowed (enforces non‑decreasing order)
backtrack = lambda do |remaining, start|
# If nothing is left, we found a valid partition
if remaining == 0
result << current.dup # store a copy because current will change
return
end
# Try all possible next values from `start` up to `remaining`
(start..remaining).each do |i|
current << i # choose i
backtrack.call(remaining - i, i) # recurse with reduced remainder
current.pop # undo the choice (backtrack)
end
end
# Start building partitions with minimum allowed value = 1
backtrack.call(n, 1)
result
end
n = 5
partitions(n).each { |p| p p }
=begin
run:
[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 4]
[2, 3]
[5]
=end