数组中求出任意几个数的和等于给的定数

package com.xxx.xxx.common;

/**
 * 数组中求出任意几个数的和等于给的定数
 * @author mdd
 * @date 2021/12/7 17:58
 */
public class SubArrSumUtil {
    int[] a = new int[]{24564, 11212, 19473, 17640, 8820, 854, 12827, 14275, 20289, 10000, 15983, 4344,854, 854, 854, 854, 34217, 17640, 12865, 3750, 24564, 24564};

    public void count(int[] a,int nc,int M){
        for(int i = 0;i < a.length; i++){

            if(i == nc){
                continue;
            }
            if(M == a[i]){
                System.out.println(a[i]);
                System.exit(1);
                return ;
            }else{
                System.out.println(a[i]);
                count(a, i,M - a[i]);
            }
        }
    }

    /**
     * 列出所有排列并求和
     * @author: mdd
     * @date: 2021/12/7 18:00
     * @param: [a, M]
     * @return: void
     */
    public void sum_M(int[] a,int M){
        int max = 1 << a.length;
        for(int i = 1;i < max - 1; i++){
            int s = 0;
            int k = a.length-1;
            int t = i;
            while(t > 0){
                if((t & 1) > 0){
                    s = s + a[k];
                }
                k--;
                t = t >> 1;
            }
            if(s == M){
                showResult(a,i,M);
            }
        }
    }

    private void showResult(int[] a, int i, int m) {
        int k = a.length - 1;
        int t = i;
        while(t > 0){
            if((t & 1) > 0){
                System.out.print("  "+a[k]);
            }
            k--;
            t = t >> 1;
        }
        System.out.print("  = "+m);
    }

    public static void main(String[] args) {
        SubArrSumUtil subArrSumUtil = new SubArrSumUtil();
        // 和
        int sum = 132975;
        subArrSumUtil.sum_M(subArrSumUtil.a, sum);
    }
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值