next_permutation的函数

转载自ACdreamers点击打开链接

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

bool next_permutation( iterator start, iterator end);

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

 

  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <string>  
  4.   
  5. using namespace std;  
  6.   
  7. int main()  
  8. {  
  9.     string str;  
  10.     cin >> str;  
  11.     sort(str.begin(),str.end());  
  12.     while (next_permutation(str.begin(), str.end()))  
  13.         cout << str << endl;  
  14.     return 0;  
  15. }  


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

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


next_permutation函数的原理如下:

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

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

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


代码:

  1. template<class Iterator>  
  2. bool next_permutation(Iterator first,Iterator last)  
  3. {  
  4.     if(first == last)  
  5.         return false;  
  6.     Iterator i = first;  
  7.     ++i;  
  8.     if(i == last)  
  9.         return false;  
  10.     i = last;  
  11.     --i;  
  12.     while(1)  
  13.     {  
  14.         Iterator t = i;  
  15.         --i;  
  16.         if(*i < *t)  
  17.         {  
  18.             Iterator j = last;  
  19.             while(!(*i < *--j));  
  20.             iter_swap(i,j);  
  21.             reverse(t,last);  
  22.             return true;  
  23.         }  
  24.         if(i == first)  
  25.         {  
  26.             reverse(first,last);  
  27.             return false;  
  28.         }  
  29.     }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值