var
n, r, i, j, k: Integer;
a, b: array [0..100] of Integer;
begin
Write('Input n, r:');
Read(n, r);
for i := 1 to r do
begin
a := i;
b := n - r + i;
end;
k := r;
j := 0;
Writeln('Combination: ');
repeat
if k = r then
begin
j := j + 1;
Write('No.', j:3, '[');
for i := 1 to r do write(a, ' ');
Writeln(']');
end;
if a[k] &lt
b[k] then
begin
a[k] := a[k] + 1;
if k &lt
r then
for k := k + 1 to r do a[k] := a[k - 1] + 1;
end
else
k := k - 1;
until k = 0;
end.
从n个数中取m个数的组合:
procedure TForm1.Button1Click(Sender: TObject);
var i,j :integer;
p : array of integer;
s : array of integer;
str : string;
begin
setlength(p,m);
for i := 0 to m-1 do p:=i;
p[m-1] := p[m-2];
setlength(s,n);
for i := 0 to n-1 do s:=i;
sum := 0;
while true do
begin
inc(p[m-1]);
str :='';
for j:=0 to length(p)-1 do
str := str+inttostr(s[p[j]])+',';
listbox1.items.add('---------------');
listbox1.items.add(str);
if p[0]=(n-m) then break;
for i:=1 to m-1 do
if p=n-(m-i) then
begin
p[i-1] := p[i-1]+1;
for j:=i to m-2 do
p[j] := p[j-1]+1;
p[m-1]:=p[m-2];
break;
end;
end;
end;
type
TForm1 = class(TForm)
ListBox1: TListBox;//用于显示结果
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
const
m = 3;//随便改,只要m<=n
n = 7;
var sum : integer;//记录当前输出的是第几个答案
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var i,j :integer;
p : array of integer;//指针数组,其内容为选取的数在s中的标号
//长度为m
s : array of integer;//源数组 长度为n
str : string;//输出结果暂存
begin
//初始化p
setlength(p,m);
for i := 0 to m-1 do p:=i;
p[m-1] := p[m-2];
//初始化s
setlength(s,n);
for i := 0 to n-1 do s:=i;//此处的赋值,可根据你的需要
sum := 0;
while true do
begin
inc(p[m-1]);
str :='';
//得到一个结果
for j:=0 to length(p)-1 do
str := str+inttostr(s[p[j]])+',';
//output
listbox1.items.add('---------------');
inc(sum);
listbox1.items.add(inttostr(sum));
listbox1.items.add(str);
//如果所有指针都排到s之末尾,则找到所有解
//结束循化
if p[0]=(n-m) then break;
//将指针往后移动
//以遍历所有的数
for i:=1 to m-1 do
if p=n-(m-i) then
begin
p[i-1] := p[i-1]+1;
for j:=i to m-2 do
p[j] := p[j-1]+1;
p[m-1]:=p[m-2];
break;
end;
end;
end;