C(b,a)表示从a个数中取b个数的无重组合,是高中数学概率的知识。
以下使用“递归方式”和“循环方式”,实现这个算法。很明显,循环的实现很简单,但是缺点是需要b是已知的才行,因为b的大小决定了for循环的个数。
public class C_Hanshu {
public static void main(String[] args) {
// 递归方式
C(new int[]{1,2,3,4,5,6,7,8,9,10},3);
System.out.println("----------------------------");
// 循环方式
C_for();
}
/**
* 递归方式:实现从a数组中,取b个元素的所有不同结果。<br>
* 可以视为c(b,a)。
*/
static int count = 0;
public static void help(int a[], int b,int begin,int index,int result[]) {
for(int i =begin;i<a.length;i++){
result[index] = a[i];
if(index < b-1){
help(a,b,i+1,index+1,result);
}else{
//输出result
System.out.print( "["+(++count)+"]");
for(int e:result)System.out.print(e+" ");
System.out.println();
}
}
}
public static void C(int a[], int b ) {
int[] result = new int[b];
help(a, b, 0, 0, result);
}
//-------------------------------------------------------------------
/**
* 循环方式:实现从10个元素的a数组中,取3个元素的所有不同结果。<br>
* 可以视为c(3,10)=(10*9*8)/(3*2*1)=120种。
*/
public static void C_for() {
int a[] = {1,2,3,4,5,6,7,8,9,10};
int result[] = new int[3];
int count = 0;
for (int i = 0; i <= 7; i++) {
result[0] = a[i];// 第一个数
for (int j = i + 1; j <= 8; j++) {
result[1] = a[j];// 第二个数
for (int k = j + 1; k <= 9; k++) {
result[2] = a[k];// 第三个数
System.out.println("["+(++count)+"]"+result[0]+" "+result[1]+" "+result[2]);//列举完3个数,则完成一次列举
}
}
}
}
}
效果:
[1]1 2 3
[2]1 2 4
[3]1 2 5
[4]1 2 6
[5]1 2 7
[6]1 2 8
[7]1 2 9
[8]1 2 10
[9]1 3 4
[10]1 3 5
[11]1 3 6
[12]1 3 7
[13]1 3 8
[14]1 3 9
[15]1 3 10
[16]1 4 5
[17]1 4 6
...
[117]7 8 9
[118]7 8 10
[119]7 9 10
[120]8 9 10
----------------------------
[1]1 2 3
[2]1 2 4
[3]1 2 5
[4]1 2 6
[5]1 2 7
[6]1 2 8
[7]1 2 9
[8]1 2 10
...
[118]7 8 10
[119]7 9 10
[120]8 9 10
--EOF--