使用遞歸實現排列組合的打印

要想使用遞歸實現排列組合首先得學會非遞歸實現排列組合
非遞歸的排列組合的實現方式如下(只允許實現1、2、3、4之間的排列組合)

package algorithm2;
import java.util.Arrays;
public class Pailiezuhe {
 int a[],b[];//a-數組(從一開始數),b-已添加的數字
 /**
  * 
  * @param number
  */
 public Pailiezuhe() {
   a= new int[4];
   for(int i=0;i<4;i++) {
    a[i] = i+1;
   }
   b = new int[4];
 }
  /**
  *  展示不同的組合
  * @return
  */
  public void show() {
	for(int j = 1;j<a.length+1;j++) {
	     a[0] = j;
	     b[0] = j;
	     for(int i = 1;i<a.length+1;i++) {
	      	if(i == b[0]) {
	       		continue;
	      	 }
	     	 a[1] = i;
	     	 b[1] = i;
	      	for(int k = 1;k<a.length+1;k++) {
	       	    if(k == b[0] || k == b[1]) {
	       		  continue;
	             }
	            a[2] = k;
	            b[2] = k;
	           for(int m = 1;m<a.length+1;m++) {
	                if(m == b[0] || m == b[1] || m == b[2]) {
	           		continue;
	                }
	               a[3] = m;
	               b[3] = m;
	               System.out.println(Arrays.toString(a));
	          }    
	       }
	     }	 
        }
 }  
}


代碼解釋:每次執行for循環代表每一位上的數字(從1到4),(第一個for循環代表第一位第二個for循環代表第二位,以此類推)
而數組b中存儲的是已經插入的數字比如第一位上數字爲1 就把1寫入數組b中並在之後的for循環中遍歷b數組,
如果之後的for循環中變量的值等於b數組中的值就直接跳過以防止之後出現相同的數字(如1,1,1,1就是例外)
按照這樣運行下去就能得到排列組合的所有結果

根據非遞歸算法,遞歸算法代碼如下:

package algorithm2;
import java.util.Arrays;
public class Nweishu {
 int a[],b[],m1 = 0;//a-數組(從一開始數),b-已添加的數字,m1-排列組合的總數
 boolean repeat; //判斷是否有重複數字
 /**
  * 
  * @param number
  */
 public Nweishu(int number) {
  if(number<0) return;
  a= new int[number];
  for(int i=0;i<number;i++) {
   a[i] = i+1;
  }
  b = new int[number];
  repeat = false;
 }
/**  展示不同的組合
  * @return
  */
 public void show() {
  show2(a,0,a.length);
  System.out.println(m1);
 }
 /**
  *  展示不同的組合
  * @param a[]-數組,N-第幾位,number-一共幾位數
  * @return
  */
  private void show2(int[] a,int N,int number) {
   if(number == 0) {
    System.out.println(Arrays.toString(a));
    m1++;
    return;
   }
   for(int i = 1;i<a.length+1;i++) {
    for(int j = 0;j<N;j++) {
     if(i == b[j]) {
      repeat = true;
     }
    }
    if(repeat == true) {
     repeat = false;
     continue;
    }
    a[N] = i;
    b[N] = i;
    show2(a,N+1,number-1);
   }
 }
public static void main(String[] args) {
  // TODO Auto-generated method stub
  new Nweishu(4).show();
 }

}

由於是第一次創作如有不足之處請多多包涵!


發佈了5 篇原創文章 · 獲贊 4 · 訪問量 4542
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章