C++ Bit manipulation Solution with O(1) space and O(2^n) time


  • 0
    Z

    The prerequisite for this method is the number of elements in nums is less or equal than the bits of integer(32).

    class Solution {
    public:

    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        unsigned int num = 1 << nums.size();
        for(int i = 0; i < num; i++) {
            vector<int> subset;
            for(int j = 0; j < nums.size(); j++) {
                if(i & (1 << j))
                    subset.push_back(nums[j]);
            }
            res.push_back(subset);
        }
        return res;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.