2009年10月7日水曜日

Java で 組み合わせ

再帰呼び出しによる組み合わせ問題のプログラム。"n1個の中からn2個を選択"。

public class Combination{

public static void main(String[] args){
combination(10, 3);
}

public static void combination(int n1, int n2){
int[] comb = new int[n2+1];
int no = 0, index= 1;

nest(no, index, n1, n2, comb);
}

public static void nest(int no, int index, int n1, int n2, int[] comb){

for(int i = no+1; i<=n1-n2+index; i++){
comb[index] = i;
if(n2 != index){
nest(i,index+1,n1,n2,comb);
}else{
for(int j = 1 ; j <= n2 ; j++){
System.out.printf(" %2d", comb[j]);
}
System.out.printf("\n");
}
}

}

}