1. Bitmask Subset Generation
Intuition
Loop mask from 0 to (1 << n) - 1. For each mask, compute curXor = 0 by XORing all nums[j] where bit j is set. Add curXor to totalSum.
When to apply: Basic simulation when verifying mathematical models.
Algorithm
- Step 1: totalSum = 0, n = nums.size().
- Step 2: Loop mask from 0 to (1 << n) - 1:
- Step 3: curXor = 0.
- Step 4: Loop j from 0 to n - 1: if mask & (1 << j): curXor ^= nums[j].
- Step 5: totalSum += curXor.
- Step 6: Return totalSum.
#include <iostream>#include <vector> using namespace std; int subsetXORSumBrute(const vector<int>& nums) { int n = nums.size(); int total = 1 << n; int sum = 0; for (int mask = 0; mask < total; ++mask) { int cur = 0; for (int j = 0; j < n; ++j) { if ((mask >> j) & 1) cur ^= nums[j]; } sum += cur; } return sum;} int main() { vector<int> nums = {1, 3}; cout << "Brute: " << subsetXORSumBrute(nums) << endl; // 6 return 0;}Time & Space Complexity
- Time complexity:
O(n * 2^n) - Space complexity:
O(1)