输入:
4 3
1 2 3 4
输出:
1 2 3
1 2 4
1 3 4
2 3 4
Delphi代码:
program select_combination;
const
max_n = 10;
var
n, m: integer;
rcd, num: array[0..max_n] of integer;
procedure select_combination(index, p: integer);
var
i: integer;
begin
if index = m then
begin
for i := 0 to m - 2 do
Write(rcd[i], ' ');
writeln(rcd[m - 1]);
exit;
end;
for i := p to n - 1 do
begin
rcd[index] := num[i];
select_combination(index + 1, i + 1);
end;
end;
var
i: integer;
begin
while not seekeof do
begin
readln(n, m);
for i := 0 to n - 1 do
Read(num[i]);
select_combination(0, 0);
end;
end.
C++代码:
#include <stdio.h>
#define MAX_N 10
int rcd[MAX_N], num[MAX_N];
int n,m;
void select_combination(int index, int p)
{
int i;
if (index == m)
{
for (i=0; i<m; i++)
{
printf("%d", rcd[i]);
if (i<m-1)
{
printf(" ");
}
}
printf("\n");
return;
}
for (i=p; i<n; i++)
{
rcd[index] = num[i];
select_combination(index+1, i+1);
}
}
int read_data()
{
int i;
if (scanf("%d%d", &n, &m)==EOF)
{
return 0;
}
for (i=0; i<n; i++)
{
scanf("%d", &num[i]);
}
return 1;
}
void main()
{
while(read_data())
{
select_combination(0, 0);
}
}