有时每次都去写全排列长长的dfs代码是很麻烦的,也因此algorithm头文件提供了两个函数——next_permutation和prev_permutation,来帮助大家减少代码量。
注:如果你连全排列都不会的话,可以先访问此网站来学习全排列的概念https://blog.csdn.net/SkeletonKing233/article/details/99676406
next_permutation函数
所在头文件:algorithm
next_permutation(a + begin, a + end, cmp);
功能:找到数组a从a[begin]开始到a[end - 1]的后一个全排列,并赋值给a[begin到a[end - 1]。
返回值:如果存在a之后的排列,就返回true。如果a是最后一个排列没有后继,返回false。
参数:
- 首地址(a + begin) 必要
- 末地址(a + end) 必要
- 比较函数表示序列如何有序(多数情况下适用于对结构体的搜索) 选要
prev_permutation函数
所在头文件:algorithm
prev_permutation(a + begin, a + end, cmp);
功能:找到数组a从a[begin]开始到a[end - 1]的前一个全排列,并赋值给a[begin到a[end - 1]。
返回值:如果存在a之前的排列,就返回true。如果a是最后一个排列没有后继,返回false。
参数:
- 首地址(a + begin) 必要
- 末地址(a + end) 必要
- 比较函数表示序列如何有序(多数情况下适用于对结构体的搜索) 选要
运行实例
备注:next_permutation与prev_permutation的本质区别是next_permutation是找a数组的后一个全排列,而prev_permutation是找a数组的前一个全排列
以下为代码(PS:NR是指数组个数的上限)
# include <cstdio>
# include <iostream>
# include <cmath>
# include <cstring>
# include <algorithm>
using namespace std;
# define FOR(i, a, b) for(int i = a; i <= b; i++)
# define _FOR(i, a, b) for(int i = a; i >= b; i--)
const int NR = 100;
int n = 3;
int a[NR + 10] = {0, 1, 2, 3};
int b[NR + 10] = {0, 3, 2, 1};
int main()
{
puts("a数组的全排列为:");
do{
FOR(i, 1, n) cout << a[i] << ' ';
puts("");
} while(next_permutation(a + 1, a + n + 1));
puts("b数组的全排列为:");
do{
FOR(i, 1, n) cout << b[i] << ' ';
puts("");
} while(prev_permutation(b + 1, b + n + 1));
return 0;
}
God Bless You For Ever!