美文网首页
给定一个数组,m个数和为n的组合

给定一个数组,m个数和为n的组合

作者: 那个阳光下奔跑的少年 | 来源:发表于2022-01-17 14:06 被阅读0次
public static List<List<Integer>> calSum(int[] arr,int n,int m){
        if(arr==null){
            return null;
        }
        List<List<Integer>> ans = new ArrayList<>();
        int len = arr.length;
        int bit = 1 << len;
        for(int i = 0;i<bit ;i++){
           if(numOf1(i)==m){
               int sum=0;
               List<Integer> list = new ArrayList<>();
               for(int j=0;j<len;j++){
                   if((i & 1 << j)!=0){
                       sum+= arr[j];
                       list.add(arr[j]);
                   }
               }
               if(sum==n){
                   ans.add(list);
               }
           }
        }
        return ans;
    }

统计一个数中二进制的个数

public static int numOf1(int n){
        int count = 0;
        while(n!=0){
            ++count;
            n = n & (n-1);
        }
        return count;
    }

相关文章

网友评论

      本文标题:给定一个数组,m个数和为n的组合

      本文链接:https://www.haomeiwen.com/subject/hyychrtx.html