概述
STL提供了两个用来计算排列组合关系的算法,分别是next_permutation(“下一个”排列组合)和prev_permutation(“前一个”排列组合)。两者都位于#include < algorithm >中。
next_permutation:把两个迭代器(或指针)指定的部分看作一个排列,求出这些元素构成的全排列中,字典序排在下一个的排列,并直接在序列上更新。另外,若不纯在排名更靠前的排列,则返回false,否则返回true。
prev_permutation:同理与next_permutation,求出这些元素构成的全排列中,字典序排在前一个的排列。
使用方式
do
{
...
} while (next_permutation(a, a + n));//prev_permutation类似
若想实现全排列,首先把数组先排序,因为next_permutation是找“下一个”排列组合。所以先将数组从小到大排序。
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
int main()
{
int a[100];
for (int i = 1; i <= 3; i++)
a[i] = i;
sort(a + 1, a + 3 + 1);
do
{
for (int i = 1; i <= 3; i++)
cout << a[i] << " ";
cout << endl;
} while (next_permutation(a + 1, a + 3 + 1));
return 0;
}
/*
输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
*/
如果我们上述代码使用的是prev_permutation,输出结果只有1 2 3;把数组从大到小排序,输出结果也只有3 2 1。
应用例子
输出一个数组中第k个全排列的序列,也就比较容易了:
int k = 0;
do
{
k++;
if (k == 1)
{
for (int i = 1; i <= 3; i++)
cout << a[i] << " ";
cout << endl;
}
} while (next_permutation(a + 1, a + 3 + 1));
或输出任意一个字符串的字典序的全排列:
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
int main()
{
string s = "bac";
sort(s.begin(), s.end());
do
{
cout << s << endl;
} while (next_permutation(s.begin(), s.end()));
return 0;
}
/*
输出:
abc
acb
bac
bca
cab
cba
*/
参考链接:原文链接