C++ 全排列函數 std::next_permutation與std::prev_permutation

C++ STL中提供了std::next_permutation與std::prev_permutation可以獲取數字或者是字符的全排列,其中std::next_permutation提供升序、std::prev_permutation提供降序。

1.std::next_permutation函數原型

  template <class BidirectionalIterator>

  bool next_permutation (BidirectionalIterator first, BidirectionalIterator last );

 

  template <class BidirectionalIterator, class Compare>

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

 

說明:next_permutation,重新排列範圍內的元素[第一,最後一個)返回按照字典序排列的下一個值較大的組合。

返回值:如果有一個更高的排列,它重新排列元素,並返回true;如果這是不可能的(因爲它已經在最大可能的排列),它按升序排列重新元素,並返回false。

2.代碼實例

複製代碼
 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 }
複製代碼

輸出:

3.算法實現原理

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

算法描述:

1、從尾部開始往前尋找兩個相鄰的元素

第1個元素i,第2個元素j(從前往後數的),且i<j

2、再從尾往前找第一個大於i的元素k。將i、k對調

3、[j,last)範圍的元素置逆(顛倒排列

發佈了72 篇原創文章 · 獲贊 29 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章