这个是C++里面用于生成全排列的函数
很好用,不仅能对数组进行全排列,还能对字符串进行全排列,但是必须保证字符串内的数组是有序的。当然,我们也可以用sort对字符串内的字符进行排序
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
string s;
s="213";
sort(s.begin(),s.end());
do{
cout << s << endl;
}while(next_permutation(s.begin(),s.end()));
system("pause");
return 0;
}
运行结果:
对于数组也是同样的使用方法
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
int a[]={1,2,3};
do{
cout << a[0] << a[1] << a[2] << endl;
}while(next_permutation(a,a+3));
system("pause");
return 0;
}
运行结果:
当然现在都是小的数字在前,大的数字在后,有没有什么办法反一反呢?
当然是有的,C++里面还带了一个prev_permutation
函数
上代码
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[]={3,2,1};
do{
cout << a[0] << a[1] << a[2] << endl;
}while(prev_permutation(a,a+3));
system("pause");
return 0;
}
运行结果: