当前位置:网站首页>leetcode1863_2021-10-14
leetcode1863_2021-10-14
2022-06-24 19:25:00 【programing菜鸟】
法一:
数组中的每个数字有选取和不选取两种状态,设数组大小为n。我们使用一个整数的前n位来模拟每个子集的选取状态,这个整数的大小由0(空集)到 (1 << n) - 1(全集)。然后我们再遍历数组,同时检查这个整数的该位,如果为1,就异或上该位;为0则直接跳过。
class Solution {
public:
int subsetXORSum(vector<int>& nums) {
int n = nums.size();
int ans = 0;
for(int i = 0; i < (1 << n); ++i){
//每一个整数i就代表一种子集
int ret = 0;
for(int j = 0; j < n; ++j){
if((i >> j) & 1) //如果i的j位为1,就异或上
ret ^= nums[j];
}
ans += ret; //加上这种子集的异或和
}
return ans;
}
};
法二:
我们使用dfs。设数组长度为n。函数dfs有三个参数,dfs(int val, int index, nums);
val代表[0, index - 1]的异或值,是已知的。而[index, n - 1]是未知的。考虑第index
位,有选取和不选取两种状态,如果选取,那么val就变成val^nums[index],如果不选取,那么val = val不变。我们利用index == n来判断结束。使用res来维护异或子集的和。
class Solution {
public:
int n;
int res;
void dfs(int val, int index, vector<int>& nums){
if(index == n){
//index == n,代表走到数组头了
res += val;
return;
}
//对两种状态分别dfs
dfs(val^nums[index], index + 1, nums);
dfs(val, index + 1, nums);
}
int subsetXORSum(vector<int>& nums) {
res = 0;
n = nums.size();
dfs(0, 0, nums);
return res;
}
};
边栏推荐
- Different WordPress pages display different gadgets
- 188. the best time to buy and sell stocks IV
- Am, FM, PM modulation technology
- Kernel Debugging Tricks
- Network flow 24 questions (round table questions)
- 为什么生命科学企业都在陆续上云?
- Multi view function in blender
- Station B takes goods to learn from New Oriental
- 力扣每日一题-第26天-496.下一个更大元素Ⅰ
- When to send the update windows message
猜你喜欢

123. 买卖股票的最佳时机 III

Tdengine can read and write through dataX

Rewrite, maplocal and maplocal operations of Charles

Page replacement of virtual memory paging mechanism

CondaValueError: The target prefix is the base prefix. Aborting.

CondaValueError: The target prefix is the base prefix. Aborting.

Implementing DNS requester with C language

Arkit与Character Creator动画曲线的对接

Simple analysis of WordPress architecture

EditText controls the soft keyboard to search
随机推荐
C语言实现DNS请求器
介绍BootLoader、PM、kernel和系统开机的总体流程
Visit Amazon memorydb and build your own redis memory database
CondaValueError: The target prefix is the base prefix. Aborting.
为什么生命科学企业都在陆续上云?
Auto. JS to automatically authorize screen capture permission
Auto. JS to realize automatic unlocking screen
Sslhandshakeexception: no subject alternative names present - sslhandshakeexception: no subject alternative names present
PIXIV Gizmo
Jar package operation
About transform InverseTransformPoint, transform. InverseTransofrmDirection
RFC 793 why to send reset and when to send reset
Tutorial on obtaining JD cookies by mobile browser
Memcached comprehensive analysis – 2 Understand memcached memory storage
一文理解OpenStack网络
Introduction to interval DP
使用Adb连接设备时提示设备无权限
Role of wait function
Pattern recognition - 0 introduction
Simple analysis of WordPress architecture