现在的位置: 首页 > 综合 > 正文

排列組合

2013年08月26日 ⁄ 综合 ⁄ 共 1222字 ⁄ 字号 评论关闭
 

排列組合

說明

將一組數字、字母或符號進行排列,以得到不同的組合順序,例如1 2 3這三個數的排列組合有:1 2 3、1 3 2、2 1 3、2 3 1、3 1 2、3 2 1。

解法

可以使用遞迴將問題切割為較小的單元進行排列組合,例如1 2 3 4的排列可以分為1 [2 3 4]、2 [1 3 4]、3 [1 2
4]、4 [1 2 3]進行排列,這邊利用旋轉法,先將旋轉間隔設為0,將最右邊的數字旋轉至最左邊,並逐步增加旋轉的間隔,例如:

1 2 3 4 -> 旋轉1 -> 繼續將右邊2 3 4進行遞迴處理

2 1 3 4 -> 旋轉1 2 變為 2 1-> 繼續將右邊1 3 4進行遞迴處理

3 1 2 4 -> 旋轉1 2 3變為 3 1 2 -> 繼續將右邊1 2 4進行遞迴處理

4 1 2 3 -> 旋轉1 2 3 4變為4 1 2 3 -> 繼續將右邊1 2 3進行遞迴處理


  1. package ceshi;  
  2.   
  3. public class Permutation {  
  4.     public static void perm(int[] num, int i) {  
  5.         if (i < num.length - 1) {  
  6.             for (int j = i; j <= num.length - 1; j++) {  
  7.                 int tmp = num[j]; // 旋轉該區段最右邊數字至最左邊  
  8.                 for (int k = j; k > i; k--)  
  9.                     num[k] = num[k - 1];  
  10.                 num[i] = tmp;  
  11.                 perm(num, i + 1); // 還原  
  12.                 for (int k = i; k < j; k++)  
  13.                     num[k] = num[k + 1];  
  14.                 num[j] = tmp;  
  15.             }  
  16.         } else { // 顯示此次排列  
  17.             for (int j = 1; j <= num.length - 1; j++)  
  18.                 System.out.print(num[j] + " ");  
  19.             System.out.println();  
  20.         }  
  21.     }  
  22.   
  23.     public static void main(String[] args) {  
  24.         int[] num = new int[4 + 1];  
  25.         for (int i = 1; i <= num.length - 1; i++)  
  26.             num[i] = i;  
  27.         perm(num, 1);  
  28.     }  

抱歉!评论已关闭.