这是一个解决方案:
def expand(n, max = n)
return [[]] if n == 0
[max, n].min.downto(1).flat_map do |i|
expand(n-i, i).map{|rest| [i, *rest]}
end
end
expand(6) # => [[6], [5, 1], [4, 2], [4, 1, 1], [3, 3], [3, 2, 1], [3, 1, 1, 1], [2, 2, 2], [2, 2, 1, 1], [2, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]