用递归和C++ next_permutation方法实现的全排列双解法探究
最编程
2024-07-27 08:20:31
...
1.递归写法
#include<iostream>
#include<algorithm>
using namespace std;
int a[5] = { 1, 2, 3, 4, 5 };
void next(int k)
{
if(k == 5)
{
for(int i = 0; i < 5; i++)
{
printf("%d ", a[i]);
}
printf("\n");
return;
}
if(k > 5) return;
for(int i = k; i < 5; i++)
{
swap(a[i], a[k]);
next(k + 1);
swap(a[i], a[k]);
}
}
int main()
{
next(0);
return 0;
}
2、next_permutation函数
技巧:next_permutation()函数是输出本排列的下一个排列!!!!。
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5;
int a[N];
int n;
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;
}
上一篇: 想当街舞红星吗?试试鸿蒙 rap 风格!
下一篇: 古埃及鼎鼎大名的法老王