在上星期的算法設計課程的學習中,我們學習了兩種全排列算法,該算法用於求出數組{1,2,3,...,n}的所有可能的排列,今天我們就來看看這個算法的具體代碼實現。
1. 第一種算法
第一種算法和我們現實生活中習慣的方法較為相似,以{1,2,3}為例,我們先寫出第一種排列123,然后將2與3交換,得到132;再回到123,交換1與2得到213,再將1與3交換.....直到得到所有的排列。
該算法偽碼如下:
PERMUTATIONS1(int n):
- for j←1 to n
- a[j]←j
- end for
- perm1(1)
perm1(int m):
- if m = n then output a[1...n]
- else
- for j←m to n
- 互換a[j]和a[m]
- perm1(m+1)
- 互換a[j]和a[m]
- end for
- end if
具體代碼實現如下:
1 //第一種排列生成算法 2 public class Permutations1 { 3 private int a[] = new int[50]; //聲明存放數據的數組 4 private int length = 0; 5 //構造函數 6 public Permutations1(int length) 7 { 8 this.length = length; 9 for(int i=1;i<=length;i++) 10 a[i] = i; 11 } 12 13 //執行全排列算法 14 public void perm1(int n) 15 { 16 if(n == length) 17 this.dispArray(); //到最底層時輸出排列結果 18 else 19 { 20 for(int i=n;i<=length;i++) 21 { 22 this.swap(i, n); //交換兩數的值 23 perm1(n + 1); //遞歸執行perm1 24 this.swap(i, n); //恢復位置 25 } 26 } 27 } 28 29 //交換數組中兩數的值 30 public void swap(int x, int y) 31 { 32 int t = a[x]; 33 a[x] = a[y]; 34 a[y] = t; 35 } 36 37 //輸出排列 38 public void dispArray() 39 { 40 for(int i=1;i<=length;i++) 41 System.out.print(a[i]); 42 System.out.println(); 43 } 44 }
2. 第二種算法
第二種算法比較類似於我們中學學的排列組合,還是以{1,2,3}為例,我們先確定第一個位置的數字3,再確定第二個位置的數字2,再確定最后一個位置的數字1,然后我們再向前恢復,再次確定第二個位置的數字....直到得到所有的排列。
該算法偽碼如下:
PERMUTATIONS2(int n):
- for j←1 to n
- a[j]←0
- end for
- perm2(n)
perm2(int m):
- if m=0 then output a[1...n]
- else
- for j←1 to n
- if a[j]=0 then
- a[j]←m
- perm2(m-1)
- a[j]←0
- end if
- end for
- end if
具體代碼如下:
1 //第二種排列生成算法 2 public class Permutations2 { 3 private int a[] = new int[50]; //聲明存放數據的數組 4 private int length = 0; //聲明數組長度 5 6 //構造函數 7 public Permutations2(int length) 8 { 9 this.length = length; 10 for(int i = 1;i<=length;i++) 11 a[i] = 0; //將所有元素記為零 12 } 13 14 public void perm2(int n) 15 { 16 if(n == 0) 17 this.dispArray(); 18 else 19 { 20 for(int i=1;i<=length;i++) 21 { 22 if(a[i] == 0) //如果該位為空 23 { 24 a[i] = n; //將n的值賦給該位 25 perm2(n - 1); //遞歸執行 26 a[i] = 0; //恢復 27 } 28 } 29 } 30 } 31 32 //輸出排列 33 public void dispArray() 34 { 35 for(int i=1;i<=length;i++) 36 System.out.print(a[i]); 37 System.out.println(); 38 } 39 }