四种情况:
1. 给定字符串,无重复
2. 给定字符串,有重复
3. 给定数字n,求1-n的所有全排列
4. 使用STL函数自带求下一个全排列函数
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
// 字符串全排列,无重复
void perm1(char* A, int cur)
{
if(cur == strlen(A)-1)
{
cout<<A<<endl;
return;
}
char temp;
for(int i=cur; i<strlen(A); i++)
{
temp = A[i];
A[i] = A[cur];
A[cur] = temp;
perm1(A,cur+1);
temp = A[i];
A[i] = A[cur];
A[cur] = temp;
}
}
// 字符串全排列,可重复
void perm2(char* A, int cur)
{
if(cur == strlen(A)-1)
{
cout<<A<<endl;
return;
}
char temp;
for(int i=cur; i<strlen(A); i++)
{
int isSwap = true;
for(int j=i; j>cur; j--){
if(A[cur] == A[j]){
isSwap = false;
}
}
if(isSwap)
{
temp = A[i];
A[i] = A[cur];
A[cur] = temp;
perm2(A,cur+1);
temp = A[i];
A[i] = A[cur];
A[cur] = temp;
}
}
}
// 求1-n的全排列,无重复
void perm3(int n, int* A, int cur){
int i,j;
if(cur == n){
for(int i=0; i<n; i++){
printf("%d",A[i]);
}
printf("\n");
return ;
}
for(int i=1; i<=n; i++){
bool ok = true;
for(int j=0; j<cur; j++){
if(A[j] == i) ok = false;
}
if(ok){
A[cur] = i;
perm3(n,A,cur+1);
}
}
}
// 求字符串全排列,可重复,std自带
void perm4(int n, int *A){
sort(A,A+n);
do{
for(int i=0; i<n ; i++) cout<<A[i]<<" ";
cout<<endl;
}while(next_permutation(A,A+n));
}
int main()
{
int A[10] = {1,2,1};
perm4(3,A);
return 0;
}