2044. 统计按位或能得到最大值的子集数目

2044. 统计按位或能得到最大值的子集数目

给你一个整数数组 nums ,请你找出 nums 子集 按位或 可能得到的 最大值 ,并返回按位或能得到最大值的 不同非空子集的数目 。

如果数组 a 可以由数组 b 删除一些元素(或不删除)得到,则认为数组 a 是数组 b 的一个 子集 。如果选中的元素下标位置不一样,则认为两个子集 不同 。

对数组 a 执行 按位或 ,结果等于 a[0] OR a[1] OR … OR a[a.length - 1](下标从 0 开始)。

示例 1:
输入:nums = [3,1]
输出:2
解释:子集按位或能得到的最大值是 3 。有 2 个子集按位或可以得到 3 :
- [3]
- [3,1]

示例 2:
输入:nums = [2,2,2]
输出:7
解释:[2,2,2] 的所有非空子集的按位或都可以得到 2 。总共有 23 - 1 = 7 个子集。

示例 3:
输入:nums = [3,2,1,5]
输出:6
解释:子集按位或可能的最大值是 7 。有 6 个子集按位或可以得到 7 :
- [3,5]
- [3,1,5]
- [3,2,5]
- [3,2,1,5]
- [2,5]
- [2,1,5]

解题思路

  1. 使用回溯法产生所有可能的子集
  2. 计算每个子集按位或的结果,比较出最大值
class Solution {
    List<List<Integer>> lists=new ArrayList<>();
    public void bc(int[] arr,int cur,LinkedList<Integer> list) {
        lists.add(new LinkedList<>(list));

        for(int i=cur;i<arr.length;i++)
        {
            list.addLast(arr[i]);
            bc(arr, i+1, list);
            list.removeLast();
        }

    }

    public List<List<Integer>> subsetsWithDup(int[] nums) {

        bc(nums,0,new LinkedList<>());
        return lists;

    }
    public int countMaxOrSubsets(int[] nums) {

        int max=0;
        subsetsWithDup(nums);
        Map<Integer,Integer> map=new HashMap<>();
        for (List<Integer> integerList : lists) {
            int cur=0;
            for (Integer integer : integerList) {
                cur|=integer;
            }
            map.put(cur,map.getOrDefault(cur,0)+1);
            max=Math.max(cur,max);
        }
        return map.get(max);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值