今天,在《算法筆記》裏面看了全排列!字節就總結一下,方便以後複習使用;
- 全排列的遞歸寫法;
這裏插入一個視頻,看了視頻就好理解了。
[算法教程] 全排列
(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