今天,在《算法笔记》里面看了全排列!字节就总结一下,方便以后复习使用;
- 全排列的递归写法;
这里插入一个视频,看了视频就好理解了。
[算法教程] 全排列
(ps:我个人觉得他的写法有问题,但是他的思想是与下面递归代码符合)
#include <iostream>
using namespace std;
void Perm(int start, int end, int a[]){
//得到全排列的一种情况,输出结果
if (start == end){
for (int i = 0; i < end; i++)
cout << a[i];
cout << endl;
return;
}
for (int i = start; i < end; i++){
swap(a[start], a[i]); //交换
Perm(start + 1, end, a); //分解为子问题a[start+1,...,end-1]的全排列
swap(a[i], a[start]); //回溯
}
}
int main() {
int i, n, a[10];
while (cin >> n, n) {
for (i = 0; i < n; i++)
{
a[i] = i + 1;
}
Perm(0, n, a);
}
return 0;
}
- 全排列的调用函数next_permutation函数;
先看一个代码:
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int a[200];
int main()
{
int i,j,n;
scanf("%d",&n);
for (i=0;i<n;i++)
a[i]=i+1;
do{
for(i=0;i<n;i++)
{
printf("%d",a[i]);
if (i<n-1)
cout<<" ";
}
cout<<endl;
}while (next_permutation(a,a+n));
return 0;
}
是不是很懵,没事,下面就有详细的介绍:
next_permutation的函数声明:#include
bool next_permutation( iterator start, iterator end);
next_permutation函数的返回值是布尔类型,在STL中还有perv_permutation()函数
以ABC为例
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
sort(str.begin(),str.end());
while (next_permutation(str.begin(), str.end()))
cout << str << endl;
return 0;
}
// 输出结果:
G:\clion\qifei\cmake-build-debug\qifei.exe
ABC
ACB
BAC
BCA
CAB
CBA
Process finished with exit code 0
next_permutation()函数功能是输出所有比当前排列大的排列,顺序是从小到大。
而prev_permutation()函数功能是输出所有比当前排列小的排列,顺序是从大到小。
next_permutation函数的原理如下:
在当前序列中,从尾端向前寻找两个相邻元素,前一个记为i,后一个记为t,并且满足i < t。然后再从尾端
寻找另一个元素j,如果满足i < *j,即将第i个元素与第j个元素对调,并将第t个元素之后(包括t)的所有元
素颠倒排序,即求出下一个序列了。
prev_permutation()函数示例:
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
while (prev_permutation(str.begin(), str.end()))
cout << str << endl;
return 0;
}
// 输出结果:
G:\clion\qifei\cmake-build-debug\qifei.exe
CBA
CAB
BCA
BAC
ACB
ABC
Process finished with exit code 0