1. Bitmask Power Set Enumeration
Intuition
Since every element can independently be either present (1) or absent (0), there are exactly 2N subsets corresponding to the binary representation of integers from 0 to 2N - 1.
Algorithm
- Step 1: Start with result list containing the empty subset [].
- Step 2: For each number in nums, iterate through all existing subsets in result.
- Step 3: Create a new subset by adding the current number to each existing subset.
- Step 4: Append all newly created subsets back into result.
- Step 5: Return result containing 2N subsets.
#include <iostream>#include <vector> class Solution {public: std::vector<std::vector<int>> subsets(std::vector<int>& nums) { int n = nums.size(); int totalSubsets = 1 << n; std::vector<std::vector<int>> result; result.reserve(totalSubsets); for (int mask = 0; mask < totalSubsets; mask++) { std::vector<int> current; for (int j = 0; j < n; j++) { if ((mask >> j) & 1) { current.push_back(nums[j]); } } result.push_back(current); } return result; }}; int main() { Solution solver; std::vector<int> nums = {1, 2, 3}; std::vector<std::vector<int>> res = solver.subsets(nums); std::cout << "Bitmask Subsets for [1, 2, 3]:\n"; for (const auto& sub : res) { std::cout << "[ "; for (int x : sub) std::cout << x << " "; std::cout << "]\n"; } return 0;}Time & Space Complexity
- Time complexity:
O(N * 2^N)— Total of 2N numbers checked, with N bit checks each. - Space complexity:
O(1) auxiliary space (excluding output)— Requires no recursive stack or temporary buffer beyond the current subset.