作者在 2010-12-29 12:43:10 发布以下内容
Generate the complete permutation of 1..N
Input
Each input file contains only one non-negative integer N (0< N < 9)
Output
Output N! Lines, according to lexicographic order.
Sample Input
3
Sample Output
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
#include <iostream>
using namespace std;
int x[9],n;
bool b[9];
void backtrace(int k)
{
int i;
if(k>n)
{
for(i=1;i<n;i++)
printf("%d ",x[i]);
printf("%d\n",x[i]);
return;
}
for(i=1;i<=n;i++)
{
if(!b[i])
{
b[i]=true;
x[k]=i;
backtrace(k+1);
x[k]=0;
b[i]=false;
}
}
}
int main()
{
int i;
scanf("%d",&n);
for(i=1;i<=n;i++)
b[i]=false;
backtrace(1);
return 0;
}
using namespace std;
int x[9],n;
bool b[9];
void backtrace(int k)
{
int i;
if(k>n)
{
for(i=1;i<n;i++)
printf("%d ",x[i]);
printf("%d\n",x[i]);
return;
}
for(i=1;i<=n;i++)
{
if(!b[i])
{
b[i]=true;
x[k]=i;
backtrace(k+1);
x[k]=0;
b[i]=false;
}
}
}
int main()
{
int i;
scanf("%d",&n);
for(i=1;i<=n;i++)
b[i]=false;
backtrace(1);
return 0;
}