classSolution { public: voiddfs(vector<int>& nums, vector<int>& path, int& ans, int start){ if (path.empty()) { ans += 0; } else { int t = 0; for (auto& i : path) { t ^= i; } ans += t; }
for (int i = start; i < nums.size(); i++) { path.push_back(nums[i]); dfs(nums, path, ans, i + 1); path.pop_back(); } } intsubsetXORSum(vector<int>& nums){ vector<int> path; int ans = 0; dfs(nums, path, ans, 0);
return ans; } };
二进制枚举
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: intsubsetXORSum(vector<int>& nums){ int n = nums.size(); int ans = 0; for (int i = 0; i < (1 << n); ++i) { int res = 0; for (int j = 0; j < n; ++j) { if (i & (1 << j)) { res = res ^ nums[j]; } } ans += res; } return ans; } };
数学公式:
1 2 3 4 5 6 7 8 9 10
classSolution { public: intsubsetXORSum(vector<int>& a){ int t = 0; for (auto i : a) { t |= i; } return t << (a.size() - 1); } };