习题2.8 输出全排列 (20point(s))
暴力递归:
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
const int MAXN=10;
int hashTable[MAXN]={false};
int P[MAXN];
int n;
void generateP(int index){
if(index>=n){
for(int i=0;i<n;++i)
cout<<P[i];
cout<<endl;
return;
}
for(int i=0;i<n;++i){
if(!hashTable[i]){
hashTable[i]=true;
P[index]=i+1;
generateP(index+1);
hashTable[i]=false;
}
}
}
int main()
{
cin>>n;
generateP(0);
}
next_permutation:
#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
using namespace std;
const int MAXN=10;
int P[MAXN];
int n;
int main()
{
cin>>n;
for(int i=0;i<n;++i)
P[i]=i+1;
do{
for(int i=0;i<n;++i)
cout<<P[i];
cout<<endl;
}while(next_permutation(P,P+n));
}