当前位置:网站首页>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;
}
};
边栏推荐
- Pattern recognition - 1 Bayesian decision theory_ P1
- [cloud native learning notes] learn about kubernetes configuration list yaml file
- 基于STM32的物联网下智能化养鱼鱼缸控制控制系统
- Shengzhe technology AI intelligent drowning prevention service launched
- MySQL optimizes query speed
- Slider控制Animator动画播放进度
- 为什么生命科学企业都在陆续上云?
- Dijkstra seeking secondary short circuit (easy to understand)
- Dynamic routing protocol rip, OSPF
- Interpretation of ebpf sockops code
猜你喜欢
Sslhandshakeexception: no subject alternative names present - sslhandshakeexception: no subject alternative names present
Blender's landscape
Memcached comprehensive analysis – 2 Understand memcached memory storage
去掉录屏提醒(七牛云demo)
VirtualBox virtual machine installation win10 Enterprise Edition
123. 买卖股票的最佳时机 III
Oauth1.0 introduction
Address mapping of virtual memory paging mechanism
Alibaba cloud lightweight servers open designated ports
Am, FM, PM modulation technology
随机推荐
About transform InverseTransformPoint, transform. InverseTransofrmDirection
EditText 控制软键盘出现 搜索
Network flow 24 questions (round table questions)
福建省发改委福州市营商办莅临育润大健康事业部指导视察工作
Advanced secret of xtransfer technology newcomers: the treasure you can't miss mentor
ping: www.baidu. Com: unknown name or service
Pattern recognition - 0 introduction
Analysis of BBR congestion control state machine
how to install clustershell
Role of wait function
Analysis of tcpdump packet capturing kernel code
66 pitfalls in go programming language: pitfalls and common errors of golang developers
力扣每日一题-第25天-496.下一个更大元素Ⅰ
基于ASP.NET开发的固定资产管理系统源码 企业固定资产管理系统源码
Antdb database online training has started! More flexible, professional and rich
PIXIV Gizmo
Return of missing persons
VirtualBox virtual machine installation win10 Enterprise Edition
虚拟货币7个月蒸发2万亿美元,“马斯克们”终结15万人暴富梦
Call process of package receiving function