这里给出一个回溯算法的源程序m对应于35,K对应于5
function TForm1.ShowComb_Back(m, k: integer): integer;
var
a:Array[0..100] of integer;
Str:String;
Count,i,j:integer;
begin
Count:=0; //count为已经找到的组合的个数
i:=0;
a[i]:=1; //i表示当前的数字为第i+1个数字
while True do
begin
//向后继续找,第i+1个数小于m-k+1,因为a[k-1]<=m,a[k-2]<=m-1,...
if a[i]-i<=m-k+1 then
begin
if i=k-1 then //找到一个组合,显示出来
begin
Inc(Count);
Str:=inttoStr(Count)+' : ';
for j:=0 to K-1 do
begin
Str:=Str+' '+InttoStr(a[j]);
end;
RichEdit1.Lines.Add(Str); //此处是显示结果的代码
Inc(a[i]);
Continue;
end
else //数字个数没有k个,继续向后找
begin
a[i+1]:=a[i]+1; 下一个数字为当前数字加上1
Inc(i);
end;
end
else //第i位后面已经全部找完,向前回溯
begin
if i=0 then 第一位为零退出
Exit
else //将前一位加1
begin
Dec(i);
inc(a[i]);
end;
end;
end;
end;
function TForm1.ShowComb_Back(m, k: integer): integer;
var
a:Array[0..100] of integer;
Str:String;
Count,i,j:integer;
begin
Count:=0; //count为已经找到的组合的个数
i:=0;
a[i]:=1; //i表示当前的数字为第i+1个数字
while True do
begin
//向后继续找,第i+1个数小于m-k+1,因为a[k-1]<=m,a[k-2]<=m-1,...
if a[i]-i<=m-k+1 then
begin
if i=k-1 then //找到一个组合,显示出来
begin
Inc(Count);
Str:=inttoStr(Count)+' : ';
for j:=0 to K-1 do
begin
Str:=Str+' '+InttoStr(a[j]);
end;
RichEdit1.Lines.Add(Str); //此处是显示结果的代码
Inc(a[i]);
Continue;
end
else //数字个数没有k个,继续向后找
begin
a[i+1]:=a[i]+1; 下一个数字为当前数字加上1
Inc(i);
end;
end
else //第i位后面已经全部找完,向前回溯
begin
if i=0 then 第一位为零退出
Exit
else //将前一位加1
begin
Dec(i);
inc(a[i]);
end;
end;
end;
end;
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货