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)范圍的元素置逆(顛倒排列

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM