Java 實現排列、組合、組合後排列!從m個裏面選n個問題!今晚筆試同程旅遊,最後一個編程題:關於排列組合的,原題的意思是:由 1,2,3,4這四個數字中選出3個數字,而後這些數最後能組合成多少個數?編程
問題一spa
由 1,2,3,4這四個數字中選出3個數字,而後這些數最後能組合成多少個數?code
先上代碼:class
public class Main { public static final int n = 3; public static int m = 4; /** * @param args */ public static void main(String[] args) { int[] array = new int[n]; f(array, 0); } public static void f(int[] array, int now) { if (now >= n) { for (int i : array) { System.out.print(i + " "); } System.out.println(); return; } else { for (int start = 1; start <= m; start++) { array[now] = start; if (j(array, now))// 判斷是否出現重複 { f(array, now + 1); } } } } public static boolean j(int[] array, int now) { for (int i = 0; i <= now; i++) { for (int j = i + 1; j <= now; j++) { if (array[i] == array[j]) { return false; } } } return true; } }
結果是程序
一共24個程序運行結果以下:總結
1 2 3 筆試
1 2 4 static
1 3 2 co
1 3 4 數字
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
問題二(排列問題)
那麼問題來了,我只想要對4個數全排列,我該怎麼作呢?只要對n的值作修改就OK了,是否是很簡單?
public class Main { public static final int n = 4;//改這個地方 public static int m = 4; /** * @param args */ public static void main(String[] args) { int[] array = new int[n]; f(array, 0); } public static void f(int[] array, int now) { if (now >= n) { for (int i : array) { System.out.print(i + " "); } System.out.println(); return; } else { for (int start = 1; start <= m; start++) { array[now] = start; if (j(array, now))// 判斷是否出現重複 { f(array, now + 1); } } } } public static boolean j(int[] array, int now) { for (int i = 0; i <= now; i++) { for (int j = i + 1; j <= now; j++) { if (array[i] == array[j]) { return false; } } } return true; } }
問題三(組合問題)
那麼問題又來了?若是咱們只是想單純的從4個數字中選3個數字,怎麼來實現呢?廢話很少說:見下面代碼,下面的代碼是基於上面加工而成,因此簡潔明瞭!
public class Main { public static final int n = 3; public static int m = 4; /** * @param args */ public static void main(String[] args) { int[] array = new int[n]; f(array, 0, 1); } public static void f(int[] array, int now, int start) { if (now >= n) { for (int i : array) { System.out.print(i + " "); } System.out.println(); return; } else { for (; start <= m; start++) { array[now] = start; f(array, now + 1, start + 1); } } } }
程序輸出結果以下:
1 2 3
1 2 4
1 3 4
2 3 4
總結:排列組合問題每每是窮舉法的一種體現形式,因此,仍是要掌握好的!