function PNM(const N,M:Integer):String;
var
A:array of Integer;
i:Integer;
procedure Gen(Level:Integer);
var
j,mm:Integer;
mstr:String;
begin
if Level=M then
begin
mstr:='';
for j:=0 to M-1do
mstr:=mstr+IntToStr(A[j])+' ';
Result:=Result+mstr+#13#10;
//速度瓶颈,最好事先分配足够大的Buffer
exit;
end;
mm:=A[Level];
for j:=Level to N-1do
begin
A[Level]:=A[j];
A[j]:=mm;
Gen(Level+1);
A[j]:=A[Level];
A[Level]:=mm;
end;
end;
begin
Result:='';
if (N<1) or (M>N) or (M<1) then
exit;
SetLength(A,N);
for i:=0 to N-1do
A:=i;
Gen(0);
end;
eg: Memo1.Text:=PNM(8,3);
0 1 2
0 1 3
0 1 4
0 1 5
0 1 6
0 1 7
0 2 1
0 2 3
......