当前位置:网站首页>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;
}
};
边栏推荐
- Station B takes goods to learn from New Oriental
- 使用 Go 编程语言 66 个陷阱:Golang 开发者的陷阱和常见错误指北
- Tdengine can read and write through dataX
- Golang reflection operation collation
- Foundations of Cryptography
- AntDB数据库在线培训开课啦!更灵活、更专业、更丰富
- Dynamic routing protocol rip, OSPF
- WMI and PowerShell get TCP connection list
- 【Camera基础(一)】Camera摄像头工作原理及整机架构
- Blender FAQs
猜你喜欢

Rewrite, maplocal and maplocal operations of Charles

Basic database syntax learning

Big factories go out to sea and lose "posture"

Sslhandshakeexception: no subject alternative names present - sslhandshakeexception: no subject alternative names present

JMeter implementation specifies concurrent loop testing

Return of missing persons

Dynamic routing protocol rip, OSPF

memcached全面剖析–5. memcached的应用和兼容程序

Memcached full profiling – 1 Fundamentals of memcached

【产品设计研发协作工具】上海道宁为您提供蓝湖介绍、下载、试用、教程
随机推荐
Implementing DNS requester with C language
VSCode无网环境快速迁移开发环境(VIP典藏版)
BPF_ PROG_ TYPE_ SOCKET_ Filter function implementation
Golang daily question
Blender's landscape
Antdb database online training has started! More flexible, professional and rich
Poj1061 frog dating (extended Euclid)
Capture the whole process of accessing web pages through Wireshark
CondaValueError: The target prefix is the base prefix. Aborting.
ping: www.baidu.com: 未知的名称或服务
EditText 控制软键盘出现 搜索
Basic database syntax learning
直击“三夏”生产:丰收喜报频传 夏播紧锣密鼓
使用 Go 编程语言 66 个陷阱:Golang 开发者的陷阱和常见错误指北
Network layer
memcached完全剖析–1. memcached的基础
Use of kubernetes storage volumes
Dijkstra seeking secondary short circuit (easy to understand)
力扣每日一题-第26天-496.下一个更大元素Ⅰ
188. 买卖股票的最佳时机 IV