leetcode1863_2021-10-14

leetcode1863 找出所有自己的异或总和再求和

法一:
数组中的每个数字有选取和不选取两种状态,设数组大小为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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值