next_permutation()从小到大
一、介绍:
- 作用:排列组合的函数,并按字典序返回。
- 在使用之前,先用sort给数据排序,然后再使用。
二、应用:
- 定义:
bool next_permutation(first,last);
first是指:数组的起始,last是指数组的末端;
int num[10]={0,1,2,3,4,5}
bool next_permutation(num+1,num+6);//将1-5排列
样例代码:
将1-4进行全排列,并输出
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int num[10];
for (int i = 1; i <= 4; i++)
num[i] = i;
sort(num + 1, num + 5); //先排序,得到最小排列
do
{
for (int i = 1; i <= 4; i++)
cout << num[i];
cout << endl;
} while (next_permutation(num + 1, num + 5)); //把下一个排列放到num中
return 0;
}
结果:
prev_permutation()从大到小排
一、介绍:
- 从大到小排序,排序前先用sort进行排序;
二、应用:
样例代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int> num;
for (int i = 1; i <= 4; i++)
num.push_back(i);
sort(num.begin(), num.end(), greater<int>()); //从大到小
do
{
for (vector<int>::iterator iter = num.begin(); iter != num.end(); iter++)
cout << *iter; //用迭代器进行遍历和输出
cout << endl;
} while (prev_permutation(num.begin(), num.end())); //从大到小排列
return 0;
}
结果: