【LetMeFly】1863.找出所有子集的异或总和再求和:位运算(二进制枚举)
力扣题目链接:https://leetcode.cn/problems/sum-of-all-subset-xor-totals/
一个数组的 异或总和 定义为数组中所有元素按位 XOR
的结果;如果数组为 空 ,则异或总和为 0
。
- 例如,数组
[2,5,6]
的 异或总和 为2 XOR 5 XOR 6 = 1
。
给你一个数组 nums
,请你求出 nums
中每个 子集 的 异或总和 ,计算并返回这些值相加之 和 。
注意:在本题中,元素 相同 的不同子集应 多次 计数。
数组 a
是数组 b
的一个 子集 的前提条件是:从 b
删除几个(也可能不删除)元素能够得到 a
。
示例 1:
输入:nums = [1,3] 输出:6 解释:[1,3] 共有 4 个子集: - 空子集的异或总和是 0 。 - [1] 的异或总和为 1 。 - [3] 的异或总和为 3 。 - [1,3] 的异或总和为 1 XOR 3 = 2 。 0 + 1 + 3 + 2 = 6
示例 2:
输入:nums = [5,1,6] 输出:28 解释:[5,1,6] 共有 8 个子集: - 空子集的异或总和是 0 。 - [5] 的异或总和为 5 。 - [1] 的异或总和为 1 。 - [6] 的异或总和为 6 。 - [5,1] 的异或总和为 5 XOR 1 = 4 。 - [5,6] 的异或总和为 5 XOR 6 = 3 。 - [1,6] 的异或总和为 1 XOR 6 = 7 。 - [5,1,6] 的异或总和为 5 XOR 1 XOR 6 = 2 。 0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28
示例 3:
输入:nums = [3,4,5,6,7,8] 输出:480 解释:每个子集的全部异或总和值之和为 480 。
提示:
1 <= nums.length <= 12
1 <= nums[i] <= 20
解题方法:二进制枚举
使用一个变量 i i i从 0 0 0到 2 n − 1 2^{n}-1 2n−1枚举,其中 i i i二进制下的每一位代表数组中每个元素的选与不选。
再用一层循环枚举每个数是否被选,异或所有本次被选择的数。
累加所有选择方案的异或结果即为所求。
- 时间复杂度 O ( n × 2 n ) O(n\times2^n) O(n×2n)
- 空间复杂度 O ( 1 ) O(1) O(1)
AC代码
C++
/*
* @Author: LetMeFly
* @Date: 2025-04-05 22:38:27
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-04-06 14:25:36
*/
class Solution {
public:
int subsetXORSum(vector<int>& nums) {
int ans = 0;
for (int i = 1 << nums.size(); i >= 0; i--) {
int thisVal = 0;
for (int j = 0; j < nums.size(); j++) {
if (i >> j & 1) {
thisVal ^= nums[j];
}
}
ans += thisVal;
}
return ans;
}
};
Python
'''
Author: LetMeFly
Date: 2025-04-06 16:17:34
LastEditors: LetMeFly.xyz
LastEditTime: 2025-04-06 16:17:54
'''
from typing import List
class Solution:
def subsetXORSum(self, nums: List[int]) -> int:
ans = 0
for i in range(1 << len(nums)):
thisCnt = 0
for j in range(len(nums)):
if i >> j & 1:
thisCnt ^= nums[j]
ans += thisCnt
return ans
Java
/*
* @Author: LetMeFly
* @Date: 2025-04-06 16:31:30
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-04-06 16:33:16
*/
class Solution {
public int subsetXORSum(int[] nums) {
int ans = 0;
for (int i = 0; i < 1 << nums.length; i++) {
int thisCnt = 0;
for (int j = 0; j < nums.length; j++) {
if ((i >> j & 1) == 1) {
thisCnt ^= nums[j];
}
}
ans += thisCnt;
}
return ans;
}
}
Go
/*
* @Author: LetMeFly
* @Date: 2025-04-06 16:34:15
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-04-06 16:37:55
*/
package main
func subsetXORSum(nums []int) (ans int) {
for i := 0; i < 1 << len(nums); i++ {
thisCnt := 0
for j := 0; j < len(nums); j++ {
if i >> j & 1 == 1 {
thisCnt ^= nums[j]
}
}
ans += thisCnt
}
return ans
}
同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~
千篇源码题解已开源