Java與演算法之(4) - 數字全排列

來源:互聯網
上載者:User

標籤:使用   tail   keyword   sdn   順序   判斷   過程   svg   highlight   

全排列是指n個數(或其他字元)所有可能的排列順序,例如1 2 3三個數位全排列是

1 2 3 
1 3 2 
2 1 3 
2 3 1 
3 1 2 
3 2 1 

那麼問題來了,任意輸入一個大於1的數字n,列出1-n這n個數位全排列。

如果嘗試手動列舉一下1 2 3的全排列,會發現通常我們會在頭腦中制定好規則,並按照既定規則進行枚舉,從而得到所有排列。

在這裡我們制定的規則是:

(想象我們手裡拿了3個數字,地上有A、B、C三個空位)

1)在每一個空位前,都按照1->2->3的順序嘗試放下一個數字,如果該數字已經放下則嘗試下一個

2)每放下一個數字後向後移動一格,然後重複1->2->3的嘗試

3)如果當前位置沒有新的可能性,取回當前位置的數字並左移一格從新嘗試

按上面規則很容易推算出第一種排列是1 2 3

取回3,返回B位置,取回2,然後按1->2->3嘗試,發現可以放下3,右移到C,嘗試後放下2,得到1 3 2

接下來必須返回到A的位置才有新的可能性,此時已經取回所有數字,按規則放下2,移到B,放下1,移到C,放下3,得到2 1 3

。。。

下面來看實現的代碼:

 

[java] view plain copy  print?
  1. public class Permutation {  
  2.   
  3.     private int max;  
  4.     private int[] array;  
  5.     private int[] hold;  
  6.       
  7.     public Permutation(int max) {  
  8.         this.max = max;  
  9.         array = new int[max + 1];  
  10.         hold = new int[max + 1];  
  11.     }  
  12.       
  13.     public void permute(int step) {  
  14.         if(step == max + 1) {  
  15.             for(int i = 1; i <= max; i++) {  
  16.                 System.out.print(array[i] + " ");  
  17.             }  
  18.             System.out.println();  
  19.             return;  //返回上一步, 即最近一次調用permute方法的後一行  
  20.         }  
  21.         //按照1->2->3->...->n的順序嘗試  
  22.         for(int num = 1; num <= max; num++) {  
  23.             //判斷是否還持有該數字  
  24.             if(hold[num] == 0) {  
  25.                 array[step] = num;  
  26.                 hold[num] = 1;  
  27.                 //遞迴: 右移一格重複遍曆數位嘗試  
  28.                 permute(step + 1);  
  29.                 //回到當前位置時取回當前位置數字  
  30.                 hold[num] = 0;  
  31.             }  
  32.         }  
  33.     }  
  34.       
  35.     public static void main(String[] args) {  
  36.         Permutation fa = new Permutation(3);  
  37.         fa.permute(1);  
  38.     }  
  39. }  

 

運行輸出

 

[java] view plain copy  print?
  1. 1 2 3   
  2. 1 3 2   
  3. 2 1 3   
  4. 2 3 1   
  5. 3 1 2   
  6. 3 2 1   

 

我們用一個偽時序圖來協助理解遞迴調用的執行過程

順便說一句,全排列問題還有多種演算法,本文中使用的是深度優先演算法的模型。

Java與演算法之(4) - 數字全排列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.