像Select[Tuples[Range[0, n], d], Total[#] == n &]
,但速度更快?枚舉Mathematica中的所有分區
更新
這裏有3個解決方案和他們那個時代的情節,IntegerPartitions其次是排列組合似乎是最快的。定時1,7,0.03遞歸,FrobeniusSolve和IntegerPartition解決方案分別
partition[n_, 1] := {{n}}; partition[n_, d_] := Flatten[Table[ Map[Join[{k}, #] &, partition[n - k, d - 1]], {k, 0, n}], 1]; f[n_, d_, 1] := partition[n, d]; f[n_, d_, 2] := FrobeniusSolve[Array[1 &, d], n]; f[n_, d_, 3] := Flatten[Permutations /@ IntegerPartitions[n, {d}, Range[0, n]], 1]; times = Table[First[Log[Timing[f[n, 8, i]]]], {i, 1, 3}, {n, 3, 8}]; Needs["PlotLegends`"]; ListLinePlot[times, PlotRange -> All, PlotLegend -> {"Recursive", "Frobenius", "IntegerPartitions"}] Exp /@ times[[All, 6]]