使用STL的next_permutation函数生成全排列(C++)

来源:互联网 发布:数据库设计经典案例 编辑:程序博客网 时间:2024/04/30 18:32

next_permutation的函数声明:#include  <algorithm>

 

bool next_permutation( iterator start, iterator end);


next_permutation函数的返回值是布尔类型,在STL中还有perv_permutation()函数

#include <iostream>#include <algorithm>#include <string>using namespace std;int main(){    string str;    cin >> str;    sort(str.begin(),str.end());    while (next_permutation(str.begin(), str.end()))        cout << str << endl;    return 0;}

next_permutation()函数功能是输出所有比当前排列大的排列,顺序是从小到大。

而prev_permutation()函数功能是输出所有比当前排列小的排列,顺序是从大到小。


next_permutation函数的原理如下:


在当前序列中,从尾端向前寻找两个相邻元素,前一个记为*i,后一个记为*t,并且满足*i < *t。然后再从尾端

寻找另一个元素*j,如果满足*i < *j,即将第i个元素与第j个元素对调,并将第t个元素之后(包括t)的所有元

素颠倒排序,即求出下一个序列了。


代码:

template<class Iterator>bool next_permutation(Iterator first,Iterator last){    if(first == last)        return false;    Iterator i = first;    ++i;    if(i == last)        return false;    i = last;    --i;    while(1)    {        Iterator t = i;        --i;        if(*i < *t)        {            Iterator j = last;            while(!(*i < *--j));            iter_swap(i,j);            reverse(t,last);            return true;        }        if(i == first)        {            reverse(first,last);            return false;        }    }}


0 0