记 n 是数组 nums 的长度,数组中的每个元素都可以选取或者不选取,因此数组的非空子集数目一共有 (2^n-1) 个。可以用一个长度为 n 比特的整数来表示不同的子集,在整数的二进制表示中,n 个比特的值代表了对数组不同元素的取舍。第 i 位值为 1 则表示该子集选取对应元素,第 i 位值为 0 则表示该子集不选取对应元素。求出每个子集的按位或的值,并计算取到最大值时的子集个数。
代码
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10
classSolution: defcountMaxOrSubsets(self, nums: List[int]) -> int: maxOr, cnt = 0, 0 for i inrange(1, 1 << len(nums)): orVal = reduce(or_, (num for j, num inenumerate(nums) if (i >> j) & 1), 0) if orVal > maxOr: maxOr, cnt = orVal, 1 elif orVal == maxOr: cnt += 1 return cnt
classSolution { public: intcountMaxOrSubsets(vector<int>& nums){ int n = nums.size(), maxValue = 0, cnt = 0, stateNumber = 1 << n; for (int i = 0; i < stateNumber; i++) { int cur = 0; for (int j = 0; j < n; j++) { if (((i >> j) & 1) == 1) { cur |= nums[j]; } } if (cur == maxValue) { cnt++; } elseif (cur > maxValue) { maxValue = cur; cnt = 1; } } return cnt; } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
intcountMaxOrSubsets(int* nums, int numsSize){ int n = numsSize, maxValue = 0, cnt = 0, stateNumber = 1 << n; for (int i = 0; i < stateNumber; i++) { int cur = 0; for (int j = 0; j < n; j++) { if (((i >> j) & 1) == 1) { cur |= nums[j]; } } if (cur == maxValue) { cnt++; } elseif (cur > maxValue) { maxValue = cur; cnt = 1; } } return cnt; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funccountMaxOrSubsets(nums []int) (ans int) { maxOr := 0 for i := 1; i < 1<<len(nums); i++ { or := 0 for j, num := range nums { if i>>j&1 == 1 { or |= num } } if or > maxOr { maxOr = or ans = 1 } elseif or == maxOr { ans++ } } return }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var countMaxOrSubsets = function(nums) { let maxOr = 0, cnt = 0; for (let i = 0; i < 1 << nums.length; i++) { let orVal = 0; for (let j = 0; j < nums.length; j++) { if (((i >> j) & 1) === 1) { orVal |= nums[j]; } } if (orVal > maxOr) { maxOr = orVal; cnt = 1; } elseif (orVal === maxOr) { cnt++; } } return cnt; };