The XOR total of an array is defined as the bitwise XOR
of all its elements, or 0
if the array is empty.
[2,5,6]
is 2 XOR 5 XOR 6 = 1
.Given an array nums
, return the sum of all XOR totals for every subset of nums
.
Note: Subsets with the same elements should be counted multiple times.
An array a
is a subset of an array b
if a
can be obtained from b
by deleting some (possibly zero) elements of b
.
Example 1:
Input: nums = [1,3] Output: 6 Explanation: The 4 subsets of [1,3] are: - The empty subset has an XOR total of 0. - [1] has an XOR total of 1. - [3] has an XOR total of 3. - [1,3] has an XOR total of 1 XOR 3 = 2. 0 + 1 + 3 + 2 = 6
Example 2:
Input: nums = [5,1,6] Output: 28 Explanation: The 8 subsets of [5,1,6] are: - The empty subset has an XOR total of 0. - [5] has an XOR total of 5. - [1] has an XOR total of 1. - [6] has an XOR total of 6. - [5,1] has an XOR total of 5 XOR 1 = 4. - [5,6] has an XOR total of 5 XOR 6 = 3. - [1,6] has an XOR total of 1 XOR 6 = 7. - [5,1,6] has an XOR total of 5 XOR 1 XOR 6 = 2. 0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28
Example 3:
Input: nums = [3,4,5,6,7,8] Output: 480 Explanation: The sum of all XOR totals for every subset is 480.
Constraints:
1 <= nums.length <= 12
1 <= nums[i] <= 20
这题是要求一个数组的所有sublist里所有元素的XOR之和。第一反应就是先把所有的sublist求出来,然后再遍历一次求出XOR和sum,应该是有点排列组合那味儿?(不确定,以后再回来revisit。)反正也是不会做,就看了答案,其实是可以一边backtrack一边求XOR的。具体看的是这篇,讲的还是挺直观的但是我懒得理解那么深入了(可能也是智商限制无法研究那么深入):- LeetCode
大意呢就是对于每个元素,我们都有取它和不取它的两种情况。我们在生成sublist的时候就可以进行XOR的计算了,我们计算取当前元素和不取当前元素两种情况的sublist XOR值,然后再把两个加起来,递归调用这个backtrack函数,直到当前已经遍历到了数组里的最后一个元素就可以停下了。这里的backtrack写的还是有返回值的,这样就可以每次都更新返回值,不需要用mutable variable in parameter了。
大概算是默写了一下答案:
class Solution {
public int subsetXORSum(int[] nums) {
return backtrack(nums, 0, 0);
}
private int backtrack(int[] nums, int index, int currXOR) {
if (index == nums.length) {
return currXOR;
}
int withElement = backtrack(nums, index + 1, currXOR ^ nums[index]);
int withoutElement = backtrack(nums, index + 1, currXOR);
return withElement + withoutElement;
}
}
有人在底下评论说这个看起来不是那么显然的backtrack,其实在计算with/withoutElement的时候把nums[index]加入和移除currXOR就相当于是在currXORArray(需要进行XOR操作的数组)里add和remove了。
还找了一个看起来比较backtrack的做法,等哪天真正要来深入理解backtrack的时候再回来看看吧:- LeetCode
太难了,我的智商不足以支撑我掌握backtrack……