1、碰到next_permutation(permutation:序列的意思)
今天在TC上碰到一道簡單題(SRM531 - Division Two - Level One),是求給定數組不按升序排列的最小字典序列(Sequence of numbers A is lexicographically smaller than B if A contains a smaller number on the first position on which they differ)。
解法很簡單,就是將數組排序(升序),然後從尾到頭找到第一個可以交換的位置(因爲可能有重複的數字)。
最後看別人的解法,排序後,用了STL中的一個函數next_permutaion,直接求到第一個不按升序排列的序列。
2、next_permutation實現原理
在《STL源碼解析》中找到了這個函數,在此也簡單敘述一下原理:
在STL中,除了next_permutation外,還有一個函數prev_permutation,兩者都是用來計算排列組合的函數。前者是求出下一個排列組合,而後者是求出上一個排列組合。所謂“下一個”和“上一個”,書中舉了一個簡單的例子:對序列 {a, b, c},每一個元素都比後面的小,按照字典序列,固定a之後,a比bc都小,c比b大,它的下一個序列即爲{a, c, b},而{a, c, b}的上一個序列即爲{a, b, c},同理可以推出所有的六個序列爲:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}沒有上一個元素,{c, b, a}沒有下一個元素。
next_permutation的函數原型如下:
template<class BidirectionalIterator>
bool next_permutation(
BidirectionalIterator _First,
BidirectionalIterator _Last
);
template<class BidirectionalIterator, class BinaryPredicate>
bool next_permutation(
BidirectionalIterator _First,
BidirectionalIterator _Last,
BinaryPredicate _Comp
);
對於第二個重載函數的第三個參數,默認比較順序爲小於。如果找到下一個序列,則返回真,否則返回假。
函數實現原理如下:
在當前序列中,從尾端往前尋找兩個相鄰元素,前一個記爲*i,後一個記爲*ii,並且滿足*i < *ii。然後再從尾端尋找另一個元素*j,如果滿足*i < *j,即將第i個元素與第j個元素對調,並將第ii個元素之後(包括ii)的所有元素顛倒排序,即求出下一個序列了。
代碼實現如下:
template<class BidirectionalIterator>
bool next_permutation(
BidirectionalIterator first,
BidirectionalIterator last
)
{
if(first == last)
return false; //空序列
BidirectionalIterator i = first;
++i;
if(i == last)
return false; //一個元素,沒有下一個序列了
i = last;
--i;
for(;;) {
BidirectionalIterator ii = i;
--i;
if(*i < *ii) {
BidirectionalIterator j = lase;
while(!(*i < *--j));
iter_swap(i, j);
reverse(ii, last);
return true;
}
if(i == first) {
reverse(first, last); //全逆向,即爲最小字典序列,如cba變爲abc
return false;
}
}
}
prev_permutation實現類似,就是反向查找
3、使用next_permutation
思考問題,序列{a, d, c, e, b}的下一個序列是什麼呢?請利用前面的分析推出答案,並用代碼驗證。
我這裏分別用數組和vector來表示序列,用next_permutation得到下一個序列(編譯環境:Dev-C++):
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void TestArray()
{
char chs[] = {'a', 'd', 'c', 'e', 'b'};
int count = sizeof(chs)/sizeof(char);
next_permutation(chs+0, chs + count);
printf("TestArray:\n");
for(int i = 0; i < count; i++) {
printf("%c\t", chs[i]);
}
printf("\n");
}
void TestVector()
{
char chs[] = {'a', 'd', 'c', 'e', 'b'};
int count = sizeof(chs)/sizeof(char);
vector<char> vChs(chs, chs + count);
next_permutation(vChs.begin(), vChs.end());
printf("TestVector:\n");
vector<char>::iterator itr;
for(itr = vChs.begin(); itr != vChs.end(); itr++) {
printf("%c\t", *itr);
}
printf("\n");
}
int main(int argc, char *argv[])
{
TestArray();
printf("\n");
TestVector();
system("PAUSE");
return EXIT_SUCCESS;
}
運行結果:
4、小結
用next_permutation和prev_permutation求排列組合很方便,但是要記得包含頭文件#include <algorithm>。
雖然最後一個排列沒有下一個排列,用next_permutation會返回false,但是使用了這個方法後,序列會變成字典序列的第一個,如cba變成abc。prev_permutation同理。