C++有專門實現全排列的函數:next_permutation(start,end),這個函數在暴力解決問題方面有很大作用,使用時需要引入頭文件 < algorithm >,噹噹前序列不存在下一個序列時就會結束,若想得到一個序列的全部排列,那麼使用前一定要記得先排序。例如:
int a[]={1,2,3,4};
do{
cout<<a[0]<<' '<<a[1]<<' '<<a[2]<<' '<<a[3]<<endl;
}while(next_permutation(a,a+4));
會輸出:
當不使用do~while,而使用while時,將不會輸出第一個序列。
當然我們也可以手寫全排列:
#include<bits/stdc++.h>
using namespace std;
int a[4]={1,2,3,4};
void swap(int &a,int &b) {
int t=a;
a=b;
b=t;
}
void AllRange(int *ptr,int k,int m) { //k表示當前選到第幾個數,m表示總共幾個數
if(k>=m) {
for(int i=0;i<m;i++) { //找完一組直接輸出
cout<<*(ptr+i);
}
cout<<endl;
}else {
for(int i=k;i<m;i++) {
swap(*(ptr+k),*(ptr+i));
AllRange(ptr,k+1,m);
swap(*(ptr+k),*(ptr+i)); //回溯
}
}
}
int main() {
AllRange(a,0,4);
}
全排列的應用可以參考第七屆藍橋杯省賽A組第六題:寒假作業