自然数を n 個に分割する & 重複組み合わせ(Ruby)

def divide(x, n) result = [] return [] if n.zero? return [[0] * n] if x.zero? return [[x]] if n == 1 0.upto(x) do |i| result += divide(x - i, n - 1).map {|a| a + [i]} end result end p divide(5, 3) 結果。5 を 3つに分割している。 [[5, 0, 0], [4, 1, 0], [3, 2, 0], [2, 3, 0], [1, 4, 0], [0, 5, 0], [4, …