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]
解題思路
- 使用回溯法產生所有可能的子集
- 計算每個子集按位或的結果,比較出最大值
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);}
}