package com.heyang;

 /** *//**
* 諸葛亮要派出五虎上將中的三員執行任務,請列出所有可能的組合
* @author 何楊(heyang78@gmail.com)
*
* @since 2009-2-11 上午08:29:25
* @version 1.00
*/
 public class Combiner {
 static char[] arr= {'關','張','趙','馬','黃'};

 public static void main(String[] args) {
int[] arr = new int[3];
combine(5, 3, arr);
}

 public static void combine(int total, int chooseCount, int selectedArr[]) {
 for (int i = total; i >= chooseCount; i--) {
selectedArr[chooseCount - 1] = i - 1;
 if (chooseCount > 1) {
combine(i - 1, chooseCount - 1, selectedArr);
}
else
 {
 for (int j = selectedArr.length - 1; j >= 0; j--) {
System.out.print(arr[selectedArr[j]] + ",");
}
System.out.println();
}
}
}
}
結果:
1 黃,馬,趙,
2 黃,馬,張,
3 黃,馬,關,
4 黃,趙,張,
5 黃,趙,關,
6 黃,張,關,
7 馬,趙,張,
8 馬,趙,關,
9 馬,張,關,
10 趙,張,關,
排列代碼:
package com.heyang;

 /** *//**
* 全排列代碼
* 趙錢孫李四人排隊,求所有排隊方案
*
* @author 何楊(heyang78@gmail.com)
*
* @since 2009-2-11 下午01:26:45
* @version 1.00
*/
 public class Permutation {
 public static void main(String[] args) {
 Character[] arr= {'趙','錢','孫','李'};
permutation(arr,0,arr.length);
}
 public static void permutation(Object[] arr,int start,int end) {
 if(start<end+1) {
permutation(arr,start+1,end);
 for(int i=start+1;i<end;i++) {
Object temp;
temp=arr[start];
arr[start]=arr[i];
arr[i]=temp;
permutation(arr,start+1,end);
temp=arr[i];
arr[i]=arr[start];
arr[start]=temp;
}
}
 else {
 for(int i=0;i<end;i++) {
System.out.print(arr[i]);
}
System.out.print("\n");
}
}
}

排列結果:
1 趙錢孫李
2 趙錢李孫
3 趙孫錢李
4 趙孫李錢
5 趙李孫錢
6 趙李錢孫
7 錢趙孫李
8 錢趙李孫
9 錢孫趙李
10 錢孫李趙
11 錢李孫趙
12 錢李趙孫
13 孫錢趙李
14 孫錢李趙
15 孫趙錢李
16 孫趙李錢
17 孫李趙錢
18 孫李錢趙
19 李錢孫趙
20 李錢趙孫
21 李孫錢趙
22 李孫趙錢
23 李趙孫錢
24 李趙錢孫
|