运行这个程序,将会输出// next_permutation example
#include <iostream> // std::cout
#include <algorithm> // std::next_permutation, std::sort
int main () {
int myints[] = {1,2,3};
std::sort (myints,myints+3);
std::cout << "The 3! possible permutations with 3 elements:\n";
do {
std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
} while ( std::next_permutation(myints,myints+3) );
std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
return 0;
}
那么我们可不可以自己写一个呢?当然可以。The 3! possible permutations with 3 elements:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
After loop: 1 2 3
//求下一个全排列
#include<cstdio>
#include<vector>
const int SIZE=10+5;
int n,a[SIZE];
void swap(int&,int&);
void reverse(int[],int);
void next_permutation(int[],int);
int main(){
scanf("%d",&n);
for(int i=0;i!=n;++i) a[i]=i+1;
int solutions=1;
for(int i=2;i!=n+1;++i) solutions*=i;
for(int i=0;i!=solutions;++i){
for(int j=0;j!=n;++j) printf("%d ",a[j]);
printf("\n");
next_permutation(a,n);
}
return 0;
}
void swap(int &m,int&n){
m^=n;
n^=m;
m^=n;
}
void reverse(int arr[],int first,int last){
int len=last-first+1;
std::vector<int>temp;
for(int i=0;i!=len;++i) temp.push_back(arr[last-i]);
for(int i=0;i!=len;++i) arr[first+i]=temp[i];
}
void next_permutation(int arr[],int len){
if (len<=1) return;//长度为0或1直接返回
int i=len-1;//i指向排列末尾
while(1){
int ii=i;
if(arr[--i]<arr[ii]){//从后往前找第一个下降的数
int j=len;
while(arr[i]>=arr[--j]);//找第一个比下降的数大的数
swap(arr[i],arr[j]);//交换这两个数
reverse(arr,ii,len-1);//将连续上升的这部分数反转变为连续下降
return;
}
if(i==0){//整个序列是单调递减的
return;//直接返回
}
}
}