给定一个整数,判断给定集合中是否存在子集之和等于该整数?

public class ChildCollection {

    public static Object isChildCollection(final int[] set, final int num) {
        //1.定义参数tempSum和tempValue,后面存储临时的值
        int tempSum,tempValue;
        //2.定义参数result,返回的结果
        boolean result = false;
        //3.使用Math.pow(底数,几次方)方法,循环2的幂次方次数,(覆盖到了所有的选择方案)
        for (int i = 0; i < Math.pow(2, set.length); i++) {
            //4.定义参数sum,存放集合的参数相加的结果
            int sum = 0;
            tempSum = i;
            for (int j = 0; j < set.length; j++) {
                //5.使用循环,判断tempSum%2是否等于1(能否除尽),等于1,集合数值相加
                if (tempSum % 2 == 1) {
                    sum += set[j];
                }
                tempSum /= 2;
            }
            //6.判断sum的结果是否和num相等,如果相等,返回true
            if (sum == num) {
                tempValue = i;
                System.out.println("存在子集合:" );
                //7.循环输出符合条件的子集合
                for(int j = 0;j < set.length;j++){
                    if(tempValue % 2 == 1){
                        System.out.print(set[j]+ "," );
                    }
                    tempValue /= 2;
                }
                System.out.println("");
                result = true;
            }
        }
        return result;
    }

        public static void main (String[]args){
            int set[] = {4, 14, 5, 9, 1, 17};
            int sum = 10;
            System.out.println(isChildCollection(set, sum));
        }
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值