一、模板
C++的algorithm库里面有一个函数next_permutation(start,end)。作用就是求一个排序的下一个排列,可以遍历全排列。注意如果不结束会一直循环,结果出现相同的排列。与之完全相反的函数还有prev_permutation(start,end),就是求一个排序的上一个排列的函数。
对于next_permutation函数,其函数原型为:
include
bool next_permutation(iterator start, iterator end)
// 当前序列不存在下一个排列时,函数返回false,否则返回true。
#include<bits/stdc++.h>
using namespace std;
int n; // n表示序列中数的个数
int a[10005];
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
do
{
for (int i = 0; i < n; i++) // 打印
cout << a[i] << " ";
cout << endl;
}while (next_permutation(a, a + n));
return 0;
}
需要强调的是,next_permutation()在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。
非模板
//z这个代码对应的一个例题
#include<bits/stdc++.h>
int cnt=0;
using namespace std;
typedef long long ll;
const int maxn=1e6+199;
int len1,len2,len3;
ll a[maxn];
int k,n,m;
void dop()
{
for (k = n - 1; k >= 1; k--)
{
if (a[k] < a[k + 1]) //找到最后可增加的位,即定位
break;
}
for (int i = n; i > k; i--)
{
if (a[i] > a[k])
{
swap(a[i], a[k]); //找到最小可增加的数字 交换
break;
}
}
sort(a + k + 1, a + n + 1); //对后面的升序排列
}
int main(){
cin>>n;
cin>>m;
for(int i=1;i<=n;i++)
cin>>a[i];
int i=0;
while(i<m)
{
i++;
dop();
}
for(int i=1;i<=n;i++)
{
if(i==1)
cout<<a[i];
else
cout<<' '<<a[i];
}
return 0;
}