当前位置:网站首页>leetcode1863_2021-10-14

leetcode1863_2021-10-14

2022-06-24 19:25:00 programing菜鸟

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;
    }
};
原网站

版权声明
本文为[programing菜鸟]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_53558968/article/details/120758908