一、next_permutation函数
#include <bits/stdc++.h>
using namespace std;
int x,n;
vector<int>s;
int main()
{
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>x;
s.push_back(x);
}
sort(s.begin(),s.end());
//使用next_permutation之前要先让数组升序排列
do
{
for(int i=0;i<n;i++)
i==n-1?printf("%d\n",s[i]):printf("%d ",s[i]);
}while(next_permutation(s.begin(),s.end()));
return 0;
}
输出1、2、3、4的全排列(尽量使小的数在前):
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
二、prev_permutation函数
#include <bits/stdc++.h>
using namespace std;
int x,n;
vector<int>s;
int main()
{
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>x;
s.push_back(x);
}
sort(s.begin(),s.end(),greater<int>());
//使用prev_permutation之前要先让数组降序排列
do
{
for(int i=0;i<n;i++)
i==n-1?printf("%d\n",s[i]):printf("%d ",s[i]);
}while(prev_permutation(s.begin(),s.end()));
return 0;
}
输出1、2、3、4的全排列(尽量使大的数在前):
4 3 2 1
4 3 1 2
4 2 3 1
4 2 1 3
4 1 3 2
4 1 2 3
3 4 2 1
3 4 1 2
3 2 4 1
3 2 1 4
3 1 4 2
3 1 2 4
2 4 3 1
2 4 1 3
2 3 4 1
2 3 1 4
2 1 4 3
2 1 3 4
1 4 3 2
1 4 2 3
1 3 4 2
1 3 2 4
1 2 4 3
1 2 3 4
参考文章:https://blog.csdn.net/howardemily/article/details/68064377