一、排列函数
元素的排列,就是我们在数学中学到的的排列,在C++ 的STL中为我们提供了内置的全排列函数 next_permutation() 和 prev_permutation(),函数原型如下:
bool next_permutation(BidirectionalIterator beg,
BidirectionalIterator end)
bool prev_permutation(BidirectionalIterator beg,
BidirectionalIterator end)
next_permutation() 会改变区间 [ beg, end) 内的元素次序,使它们符合 “ 下一个排列次序 ”。
prev_permutation() 会改变区间 [ beg, end) 内的元素次序,使它们符合 “ 上一个排列次序 ”。
其元素按字典次序变化,next_permutation() 为升序, prev_permutation() 为降序,若要走遍所有排列,需要先将所有元素(按升序或降序)排列,然后以循环的方式调用函数,直至算法返回 false;
对于n个元素,全排列后有 n! 种排列方式,且最多n/2次交换,n为区间长度,平均每次调用使用了3次比较和1.5次交换,时间复杂度为O(n);
二、函数的使用
使用 next_permutation() 和 prev_permutation(),需声明其头文件 #include <algorithm>
和 using namespace std
。
1、基础使用
例如 输出“下一个” 或 “上一个” 序列:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int a[5] = {
1,3,5,4,2};
int b[5] = {
1,3,5,4,2};
int copy_a[5] = {
1,3,