我需要一个算法来打印数字(分区)的所有可能的总和。 例如:5我要打印:全部数字
1+1+1+1+1
1+1+1+2
1+1+3
1+2+2
1+4
2+3
5
我在写帕斯卡尔我的代码。到目前为止,我有这样的:
Program Partition;
Var
pole :Array [0..100] of integer;
n :integer;
{functions and procedures}
function Minimum(a, b :integer): integer;
Begin
if (a > b) then Minimum := b
else Minimum := a;
End;
procedure Rozloz(cislo, i :integer);
Var
j, soucet :integer;
Begin
soucet := 0;
if (cislo = 0) then
begin
for j := i - 1 downto 1 do
begin
soucet := soucet + pole[j];
if (soucet <> n) then
Write(pole[j], '+')
else Write(pole[j]);
end;
soucet := 0;
Writeln()
end
else
begin
for j := 1 to Minimum(cislo, pole[i - 1]) do
begin
pole[i] := j;
Rozloz(cislo - j, i + 1);
end;
end;
End;
{functions and procedures}
{Main program}
Begin
Read(n);
pole[0] := 101;
Rozloz(n, 1);
Readln;
End.
它的工作好,但不是输出我想我得到这个:
1+1+1+1+1
2+1+1+1
2+2+1
3+1+1
3+2
4+1
5
我无法弄清楚如何打印在正确的道路。感谢您的帮助
编辑:更改for j:=i-1 downto 1
到for j:=1 to i-1
解决了一个问题。但我的输出仍然是这样的:(1 + 1 + 1 + 1 + 1)(2 + 1 + 1 + 1)(2 + 2 + 1)(3 + 1 + 1)(3 + 2)(4 + 1 )(5)但它应该是:(1 + 1 + 1 + 1 + 1)(1 + 1 + 1 + 2)(1 + 1 + 3)(1 + 2 + 2)(1 + 4) +3)(5)主要问题是与第五和第六元素。他们应该是相反的顺序。
是唯一错误的顺序?你想要增加订单而不是减少?如果是这样的话,我认为你可以将倒数第1次的“for j:= i-1 downto 1”从倒数计数到...从1增加到i-1。你的算法似乎只是先找到最大的数字(因为这个j开始很大)。 – TravisJ 2014-12-06 18:03:59
这解决了一个问题,但是我的输出仍然是这样的: (1 + 1 + 1 + 1 + 1) (2 + 1 + 1 + 1) (2 + 2 + 1) (3+ 1 + 1) (3 + 2) (4 + 1) (5) 但它应该是: (1 + 1 + 1 + 1 + 1) (1 + 1 + 1 + 1) (1 + 1 + 3) (1 + 2 + 2) (1 + 4) (2 + 3) (5) 问题也与第5和第6元素。他们应该是相反的顺序。 – Superian007 2014-12-06 18:39:45
@TravisJ有什么想法? – Superian007 2014-12-06 21:32:02