C++进阶:STL算法18--排列组合算法

1. 简介

函数 作用 文档
next_permutation(beg,end) 取出[beg,end)内的下移一个排列。 next_permutation()
next_permutation(beg,end,comp) 将函数comp代替<操作符,执行next_permutation() next_permutation()
prev_permutation(beg,end) 取出[beg,end)内的上移一个排列。 prev_permutation()
prev_permutation(beg,end,comp) 将函数comp代替<操作符,执行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. 练习

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 13,039评论 0 33
  • //leetcode中还有花样链表题,这里几个例子,冰山一角 求单链表中结点的个数----时间复杂度O(n)这是最...
    暗黑破坏球嘿哈阅读 1,702评论 0 6
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,356评论 25 708
  • 小爪1002阅读 237评论 0 0
  • 此时再回想,最初推开张正的那一瞬间,毛儒毅并没有认出站在张正身后的是罗森。 他只是看到了一张狰狞而可怕的脸,面孔上...
    樹里阅读 219评论 0 0

友情链接更多精彩内容