输入:
3
1 2 3
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
Delphi代码:
program full_permutation;
//全排列
const
max_n = 10;
var
n: integer;
rcd, used, num: array[0..max_n] of integer;
procedure full_permutation(index: integer);
var
i: integer;
begin
if index = n then
begin
for i := 0 to n - 2 do
Write(rcd[i], ' ');
writeln(rcd[n - 1]);
exit;
end;
for i := 0 to n - 1 do
if used[i] = 0 then
begin
used[i] := 1;
rcd[index] := num[i];
full_permutation(i + 1);
used[i] := 0;
end;
end;
var
i: integer;
begin
while not seekeof do
begin
readln(n);
for i := 0 to n - 1 do
Read(num[i]);
FillChar(used, sizeof(used), 0);
full_permutation(0);
end;
end.
C++代码:
#include <stdio.h>
#include <string.h>
#define MAX_N 10
int n;
int rcd[MAX_N], used[MAX_N], num[MAX_N];
void full_permutation(int index)
{
int i;
if (index == n)
{
for (i = 0; i < n ; i++)
{
printf("%d", rcd[i]);
if(i<n-1) printf(" ");
}
printf("\n");
return;
}
for (i=0; i<n; i++)
{
if (!used[i])
{
used[i] = 1; //标记
rcd[index] = num[i]; //在index位置上放上该数
full_permutation(index+1);
used[i] = 0; //清除标记
}
}
}
int read_data()
{
int i;
if (scanf("%d", &n)== EOF)
{
return 0;
}
for (i = 0; i < n ; i++)
{
scanf("%d", &num[i]);
}
memset(used, 0, sizeof(used));
return 1;
}
void main()
{
while(read_data())
{
full_permutation(0);
}
}