今天刷到一题需要计算一个数组的全排列问题,在几经周折终于用代码实现了,可是后来在阅读dalao的解题思路是,突然间发现了一个神奇的函数next_permutation
先附上全排列递归实现的代码:
#include<cstdio>
const int maxn = 11;
int n,P[maxn],hashTable[maxn] = {false};
void generateP(int index){
if(index == n+1){
for(int i = 1;i <= n;i++){
printf("%d",P[i]);
}
printf("\n");
return;
}
for(int x = 1;x <= n;x++){
if(hashTable[x] == false){
P[index] = x;
hashTable[x] = true;
generateP(index + 1);
hashTable[x] = false;
}
}
}
int main(){
n = 5;
generateP(1);
return 0;
}
--------------------------------------------------------------------------------------
接下来讲一下这个方便的函数next_permutation
使用注意事项,先排序,再使用
头文件:#include<algorithm>
函数原型 bool next_permutation(iterator start,iterator end)
函数说明:start和end是数组需要全排列的范围,若存在下一个排列返回true,否则返回false;
例子:
#include<cstdio>
#include<algorithm>
using namespace std;
int main(){
int a[3] = {1,2,3};
do{
printf("%d%d%d\n",a[0],a[1],a[2]);
}while(next_permutation(a,a+3));
return 0;
}
输出:
123
132
213
231
312
321