STL提供求下一个排列组合函数next_permutation(),该函数被定义于头文件algorithm。
全排列定义: 从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。
公式: 全排列数f(n)=n!(定义0!=1)
函数next_permutation()的定义有两种形式:
//第一种
template< class BidirIt >
bool next_permutation( BidirIt first, BidirIt last );
//第二种
template< class BidirIt, class Compare >
bool next_permutation( BidirIt first, BidirIt last, Compare comp );
//第一个种使用<来确定顺序,而第二个种则使用 comp比较对象。
//第二种方法中的第三个参数为比较函数对象
复杂度: O(n)
排列范围: [first,last),包括first,不包括last。
返回值:如果没有下一个排列组合,返回false,否则返+回true。
每执行next_permutation()一次,就会把新的排列放到原来的空间里。
注意:
在使用next_permutation()的时候,初始序列一般是一个字典序最小的序列,如果不是,可以使用sort()排序,
得到最小序列,然后再使用next_permutation()。
next_permutation的一种实现方法:
template<class BidirIt>
bool next_permutation(BidirIt first, BidirIt last)
{
if (first == last) return false;
BidirIt i = last;
if (first == --i) return false;
while (true) {
BidirIt i1, i2;
i1 = i;
if (*--i < *i1) {
i2 = last;
while (!(*i < *--i2))
;
std::iter_swap(i, i2);
std::reverse(i1, last);
return true;
}
if (i == first) {
std::reverse(first, last);
return false;
}
}
}
使用方法:
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
std::string s = "aba";
std::sort(s.begin(), s.end());
do {
std::cout << s << '\n';
} while(std::next_permutation(s.begin(), s.end()));
}
输出:
aab
aba
baa
与next_permutation()相关函数:
1. prev_permutation():求前一个排列组合
2. 2. lexicographical_compare():字典比较