3

The XOR sum of an array is defined as the result of the bitwise XOR of all elements in the array; if the array is empty, the XOR sum is 0.

For example, the XOR sum of the array [2,5,6] is 2 XOR 5 XOR 6 = 1 .
Given an array nums , ask you to find the XOR sum of each subset in nums, compute and return the sum of these values.
Note: In this problem, different subsets with the same elements should be counted multiple times.
Array a is a subset of array b if a is obtained by removing a few (or possibly none) elements from b.

Example 1:

 输入:nums = [1,3]
输出:6
解释:[1,3] 共有 4 个子集:
- 空子集的异或总和是 0 。
- [1] 的异或总和为 1 。
- [3] 的异或总和为 3 。
- [1,3] 的异或总和为 1 XOR 3 = 2 。
0 + 1 + 3 + 2 = 6

Example 2:

 输入:nums = [5,1,6]
输出:28
解释:[5,1,6] 共有 8 个子集:
- 空子集的异或总和是 0 。
- [5] 的异或总和为 5 。
- [1] 的异或总和为 1 。
- [6] 的异或总和为 6 。
- [5,1] 的异或总和为 5 XOR 1 = 4 。
- [5,6] 的异或总和为 5 XOR 6 = 3 。
- [1,6] 的异或总和为 1 XOR 6 = 7 。
- [5,1,6] 的异或总和为 5 XOR 1 XOR 6 = 2 。
0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28

Example 3:

 输入:nums = [3,4,5,6,7,8]
输出:480
解释:每个子集的全部异或总和值之和为 480 。

Problem solving ideas

  1. Find all possible cases using backtracking basic processing;
  2. Use the accumulator XOR to get the sum of all values;

problem solving code

 var subsetXORSum = function (nums) {

    let ans = 0;

    //回溯

    let backTracing = (start, path) => {

        if (path.length) {

            //计算异或后的值

            ans+= path.reduce((acc, cur) => acc ^= cur, 0)

        }

        //回溯基本处理

        for (let i = start; i < nums.length; i++) {

            path.push(nums[i])

            backTracing(i + 1, path)

            path.pop()

        }

    }

    backTracing(0, [])

    return ans;

};

微芒不朽
1.2k 声望1.3k 粉丝