1. 程式人生 > >Java: 演算法 - 1,2,3,4 取3個數組成三位數字,求能排列組合數量,並將它們打印出來

Java: 演算法 - 1,2,3,4 取3個數組成三位數字,求能排列組合數量,並將它們打印出來

涉及數學公式:

A n m = n ! (

n m ) ! A^m_n=\frac{n!}{(n-m)!} (n個數取m個排列組合) permutation and combination
C
n m = n ! m ! (
n m ) !
C^m_n=\frac{n!}{m!(n-m)!}
(n個數取m個組合) combination

分析1,2,3,4取3個數字排列組合,應用數學公式 A 4 3 = 4 ! ( 4 3 ) ! A^3_4 = \frac{4!}{(4-3)!} = 24 種排列組合

1. 如果只求排列組合數量,可以直接使用數學公式

用程式碼表示:

public static long pnc(int n, int m){

	long numerator  = 1;
	for(;n>1;n--){
		numerator = numerator*n;
	}
	
	long denominator = 1;
	for(int i=n-m;i>1;i--){
		denominator = denominator*i;
	}
	
	return numerator/denominator;
}

測試:

public static void main(String args[]){
	System.out.println(pnc(4,3));
}

輸出:

24

2. 列印的話,使用窮舉法

程式碼:

public static void pnc(){
	long pnc = 0;
  	for(int i=1;i<=4;i++){
  		for(int j=1;j<=4;j++){
  			for(int k=1;k<=4;k++){
  				if(i!=j && i!=k && j!=k){
  					pnc++;
  					int num = i*100+j*10+k;
  					System.out.print(num + " "); 
  				}
  			}
  		}
  	}
	System.out.println("\n" + "Permutations and Combinations: "+ pnc ); 
}

if程式碼塊可以用Stringbuffer寫

if(i!=j && i!=k && j!=k){
	pnc++;
	StringBuffer num = new StringBuffer();
	num.append(i);
	num.append(j);
	num.append(k);
	num.append(" ");
	System.out.print(num);
}

測試:

public static void main(String args[]){
	pnc();
}

輸出:

123 124 132 134 142 143 213 214 231 234 241 243 312 314 321 324 341 342 412 413 421 423 431 432
Permutations and Combinations: 24