全排列
输入整数n,列举出全排列的所有情况。
#include<iostream>
using namespace std;
int n;
void pathAdd(int *path,int a){
for(int i=0;i<n;i++){
if(path[i]==0){
path[i]=a; break;
}
}
}
void copyarray(int *a,int *b){
for(int i=0;i<n;i++){
a[i]=b[i];
}
}
void FullPermutation(int depth, bool used[],int path[]){
if(depth==n){
for(int i=0;i<n;i++)
cout<<path[i]<<" ";
cout<<endl;
return;
}
for(int i=1;i<=n;i++){
if(!used[i]){
int tempPath[n]; copyarray(tempPath,path);
pathAdd(path,i);
used[i]=true;
//递归进入下一层
FullPermutation(depth+1,used,path);
//回溯,回到递归前的状态
copyarray(path,tempPath);
used[i]=false;
}
}
}
int main(){
cin>>n;
bool used[n];
int path[n];
for(int i=0;i<n;i++){
path[i]=0;used[i]=false;
}
FullPermutation(1,used,path);
return 0;
}