【題目】設計一個遞歸算法生成n個元素{r1,r2,…,rn}的全排列。
【算法講解】
設R={r1,r2,…,rn}是要進行排列的n個元素,Ri=R-{ri}。
集合X中元素的全排列記為perm(X)。
(ri)perm(X)表示在全排列perm(X)的每一個排列前加上前綴得到的排列。
R的全排列可歸納定義如下:
當n=1時,perm(R)=(r),其中r是集合R中唯一的元素;
當n>1時,perm(R)由(r1)perm(R1),(r2)perm(R2),…,(rn)perm(Rn)構成。
實現思想:將整組數中的所有的數分別與第一個數交換,這樣就總是在處理后n-1個數的全排列。
【示例】
當n=3,並且E={a,b,c},則:
perm(E)=a.perm({b,c}) + b.perm({a,c}) + c.perm({a,b})
perm({b,c})=b.perm(c) + c.perm(b)
a.perm({b,c})=ab.perm(c) + ac.perm(b)
=ab.c + ac.b=(abc, acb)
1 template<class Type> 2 void Perm(Type list[],int k,int m){ 3 if(k==m){ 4 for( int i=0; i<=m; i++ ) 5 cout<<list[i]; 6 cout<<endl; 7 } 8 else{ 9 for( int i=k; i<=m; i++ ){ 10 Swap(list[k],list[i]); 11 Perm(list,k+1,m); 12 Swap(list[k],list[i]); 13 } 14 } 15 } 16 template<class Type> 17 inline void Swap(Type &a,Type &b){ 18 Type temp = a; 19 a=b; 20 b=temp; 21 }
下面是完整代碼:
1 #include <iostream> 2 #include <algorithm> 3 4 using namespace std; 5 6 template<class Type> 7 void Perm(Type list[], int k, int m ) 8 { //產生[list[k:m]的所有排列 9 if(k==m) 10 { //只剩下一個元素 11 for (int i=0;i<=m;i++) 12 cout<<list[i]; 13 cout<<endl; 14 } 15 else //還有多個元素待排列,遞歸產生排列 16 for (int i=k; i<=m; i++) 17 { 18 swap(list[k],list[i]); 19 Perm(list,k+1,m); 20 swap(list[k],list[i]); 21 } 22 } 23 24 int main() { 25 26 char s[]="abc"; 27 Perm(s,0,2); 28 29 return 0; 30 }