C++ 全排列函数 std::next_permutation与std::prev_permutation

C++ STL中提供了std::next_permutation与std::prev_permutation能够获取数字或者是字符的全排列,其中std::next_permutation提供升序、std::prev_permutation提供降序。ios

1.std::next_permutation函数原型算法

  template <class BidirectionalIterator>函数

  bool next_permutation (BidirectionalIterator first, BidirectionalIterator last );oop

 

  template <class BidirectionalIterator, class Compare>spa

  bool next_permutation (BidirectionalIterator first,BidirectionalIterator last, Compare comp);code

 

说明:next_permutation,从新排列范围内的元素[第一,最后一个)返回按照字典序排列的下一个值较大的组合。blog

返回值:若是有一个更高的排列,它从新排列元素,并返回true;若是这是不可能的(由于它已经在最大可能的排列),它按升序排列从新元素,并返回false。原型

2.代码实例it

 1 #include <iostream>
 2 #include <algorithm>    /// next_permutation, sort
 3 using namespace std;
 4 int main () {
 5   int myints[] = {1,2,3,1};
 6   sort (myints,myints+4);
 7 
 8   do {
 9     cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << ' '<< myints[3]<<'\n';
10   } while ( next_permutation(myints,myints+4) );    ///获取下一个较大字典序排列
11 
12   cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << ' '<< myints[3] <<'\n';
13   return 0;
14 }

输出:io

3.算法实现原理

见:http://hi.baidu.com/bellgrade/item/70b65b8a7ea3c9c398255fd4

算法描述:

一、从尾部开始往前寻找两个相邻的元素

第1个元素i,第2个元素j(从前日后数的),且i<j

二、再从尾往前找第一个大于i的元素k。将i、k对调

三、[j,last)范围的元素置逆(颠倒排列

相关文章
相关标签/搜索