2014-12-06 41 views
0

我需要一个算法来打印数字(分区)的所有可能的总和。 例如: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 1for 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)主要问题是与第五和第六元素。他们应该是相反的顺序。

+3

是唯一错误的顺序?你想要增加订单而不是减少?如果是这样的话,我认为你可以将倒数第1次的“for j:= i-1 downto 1”从倒数计数到...从1增加到i-1。你的算法似乎只是先找到最大的数字(因为这个j开始很大)。 – TravisJ 2014-12-06 18:03:59

+0

这解决了一个问题,但是我的输出仍然是这样的: (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

+0

@TravisJ有什么想法? – Superian007 2014-12-06 21:32:02

回答

0

我不会尝试Pascal,但这里是一个解决方案的伪代码,它以您想要的顺序打印内容。

procedure print_partition(partition); 
    print "(" 
    print partition.join("+") 
    print ") " 

procedure finish_and_print_all_partitions(partition, i, n): 
    for j in (i..(n/2)): 
     partition.append(j) 
     finish_and_print_all_partitions(partition, j, n-j) 
     partition.pop() 
    partition.append(n) 
    print_partition(partition) 
    partition.pop() 

procedure print_all_partitions(n): 
    finish_and_print_all_partitions([], 1, n) 
+0

你所包含的“伪代码”与Pascal没有任何关系,因此它不是对这里提出的问题的回答。 – 2014-12-06 21:59:16

+0

@KenWhite请求是针对算法而不是代码。我给出的伪代码表达了一种算法,可以将其转换成任何支持递归的命令式语言,包括Pascal。因此,这是对问题的回答。 – btilly 2014-12-07 00:16:45

+0

这张海报显然不能将该伪代码翻译成Pascal;他们在安排现有代码的输出时遇到了麻烦(如果你阅读的不止是开头句子的前四个单词,那么问题实际上就是这样问的)。你的回答说:“好吧,我不会试图回答你关于A的问题,但我会给你一些与隐约讨论Z无关的文字。” – 2014-12-07 00:20:49