忘了从哪看过的题目了,今天实现了一下,本来试着用m个指针的,后发现实现比较麻烦,可能递归的话就简单了;我用的是int[]模拟二进制+1操作,0表示无,1表示有,当二进制数组+1后,有m个1,则认为是一组组合。
代码如下:
private List<int[]> numList;
/**
* input : n , m
* output : display the combinations for (select m numbers from n)
* @param n
* @param m
*/
public void outputCombinationNumbers(int n, int m){
List<int[]> arrayList = new ArrayList<int[]>();
int[] b = new int[n];
add1ForBits(b, m);
if(numList != null){
System.out.println(JSON.toJSON(numList));
}
}
/**
*
* @param b
* @param m
*/
public void add1ForBits(int[] b, int m){
numList = new ArrayList<int[]>();
int[] a = null;
if(b == null){
return;
}
int count1 = 0;
int length = b.length;
int lcount = (int)Math.pow(2.0, length + 0.0);
for(int i=1;i<lcount;i++){
a = new int[m];
if(add1ForBitArray(b, m, a)){
numList.add(a);
}
}
}
/**
* 为数组末尾加1,如有进位则继续向前+1,同时判断是否已经有多余m个的1,如有则终止,否则继续进位操作/统计1的个数
* @param b
* @param int[] a , 返回m个1的位置
* @return true 进位,false 不进位
*/
private boolean add1ForBitArray(int[] b, int m, int[] a){
boolean flag = true;
if(b == null){
return false;
}
int length = b.length;
int count = 0;
for(int i=length-1;i>=0;i--){
if(b[i] == 0){
if(flag){
b[i] = 1;
flag = false;
count++;
if(count > m){
return false;
}
a[count-1] = i;
}
} else {
if(flag){
b[i] = 0;
}else {
count++;
if(count > m){
return false;
}
a[count-1] = i;
}
}
}
if(count == m){
return true;
}
return false;
}
欢迎转载评论,有更好的方法欢迎交流。