C++ STL全排列 next_permutation 用法

C++ STL全排列 next_permutation 用法

全排列是排列数学中常用的算法之一,而C++ STL中就提供了内置的全排列函数 next_permutation.

方法原型主要有以下两种(均以经过个人简化)

template<class Iterator>
  bool next_permutation (Iterator first, Iterator last);

template<class Iterator, class Compare>
  bool next_permutation (Iterator first, Iterator last, Compare comp);

next_permutation是一个原地算法(会直接改变这个集合,而不是返回一个集合),它对一个可以遍历的集合(如string,如vector),将迭代器范围 [first, last] 的排列 排列到下一个排列(第一个是名词,第二个是动词,第三个是名词),其中所有排列的集合默认按照operator < 或者 字典序 或者 按照输入到第三个参数 comp 的排列方法排列。如果存在这样的“下一个排列”,返回true并执行排列,否则返回false。

听起来有点抽象,我们直接举个很简单的例子,字符串“123”的按照字典序正确的全排列是:

"123" "132" "213" "231" "312" "321"

执行以下程序

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
  string number = "213";
  next_permutation( number.begin(), number.end());
  cout << number;
  
  return 0;
}

此时输出得到的是 "231"

如果我们想得到一个序列的完整全排列,可以这样

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
  vector<char> chars = {'a', 'b', 'c'};
  do {
    cout << chars[0] << chars[1] << chars[2] << endl;
  } while ( next_permutation( chars.begin(), chars.end()));
  
  return 0;
}

输出结果为

abc
acb
bac
bca
cab
cba
posted @ 2020-09-05 16:12  scyq  阅读(520)  评论(0编辑  收藏  举报