不知他们用C是怎样实现的,我是这样实现的:
#include<iostream.h>
const int M=20;
const int N=4;
static int Num[N];
void GetNum(int SumNum,const int m,const int n,int l)
{
int i,j;
for(i=l;i<=m-n;i++)
{
if ((l>1) &&
(i<=Num[l-2]))
continue;
Num[l-1]=i;
if (l!=n)
GetNum(SumNum+i,m,n,l+1);
else
if (SumNum+i==m)
{
for(j=0;j<n;j++)
cout<<Num[j]<<" ";
cout<<"/n";
}
}
}
void main()
{
GetNum(0,M,N,1);
}
用Delphi只要转换一下
program Project2;
{$APPTYPE CONSOLE}
uses SysUtils;
const
M=20;
N=4;
var
Num:Array[0..N-1] of Integer;
Procedure GetNum(SumNum:Integer;
m:Integer;n:Integer;l:Integer);
var
i,j:Integer;
begin
for i:=l to m-n do
begin
if ((l>1) and (i<=Num[l-2])) then
continue;
Num[l-1]:=i;
if (l<>n) then
GetNum(SumNum+i,m,n,l+1)
else
if (m=(SumNum+i)) then
begin
for j:=0 to n-1 do
begin
write(Num[j]);
write(' ');
end;
writeln('');
end;
end;
end;
begin
// Insert user code here
GetNum(0,M,N,1);
readln;
end.
更大的数我就没测试了。