算法:输出从n个数中任意取m个数的组合

忘了从哪看过的题目了,今天实现了一下,本来试着用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;
    }


欢迎转载评论,有更好的方法欢迎交流。

转载于:https://my.oschina.net/cwzhang/blog/214917

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值