C++進階:STL算法18--排列組合算法

1. 簡介

函數(shù) 作用 文檔
next_permutation(beg,end) 取出[beg,end)內(nèi)的下移一個排列。 next_permutation()
next_permutation(beg,end,comp) 將函數(shù)comp代替<操作符,執(zhí)行next_permutation()。 next_permutation()
prev_permutation(beg,end) 取出[beg,end)內(nèi)的上移一個排列。 prev_permutation()
prev_permutation(beg,end,comp) 將函數(shù)comp代替<操作符,執(zhí)行prev_permutation()。 prev_permutation()

2. 示例代碼

  • next_permutation
// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort

int main () {
  int myints[] = {1,2,3};

  std::sort (myints,myints+3);

  std::cout << "The 3! possible permutations with 3 elements:\n";
  do {
    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::next_permutation(myints,myints+3) );

  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}
  • prev_permutation
// next_permutation example
#include <iostream>     // std::cout
#include <algorithm>    // std::next_permutation, std::sort, std::reverse

int main () {
  int myints[] = {1,2,3};

  std::sort (myints,myints+3);
  std::reverse (myints,myints+3);

  std::cout << "The 3! possible permutations with 3 elements:\n";
  do {
    std::cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';
  } while ( std::prev_permutation(myints,myints+3) );

  std::cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;
}

3. 練習

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,896評論 0 33
  • //leetcode中還有花樣鏈表題,這里幾個例子,冰山一角 求單鏈表中結點的個數(shù)----時間復雜度O(n)這是最...
    暗黑破壞球嘿哈閱讀 1,646評論 0 6
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,856評論 25 709
  • 小爪1002閱讀 225評論 0 0
  • 此時再回想,最初推開張正的那一瞬間,毛儒毅并沒有認出站在張正身后的是羅森。 他只是看到了一張猙獰而可怕的臉,面孔上...
    樹里閱讀 206評論 0 0

友情鏈接更多精彩內(nèi)容