C++, 8 lines, bit operation


  • 3
    T

    Please note this solution does not work when nums.size() > 32.

    vector<int> helper(vector<int>& nums, int magic){
        vector<int> rtn = {};
        for(int i = 0; i < nums.size(); i++)
            if(((1 << i) & magic) != 0) rtn.push_back(nums[i]);
        return rtn;
    }
    
    vector<vector<int> > subsets(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        
        vector<vector<int> > rtn = {};
        for(int i = 0; i < (1 << nums.size()); i++) rtn.push_back(helper(nums, i));
        
        return rtn;
    }

  • 0
    T

    FYI, to support size > 32, you can use the c++ build-in library bitset, see this link: http://www.cplusplus.com/reference/bitset/bitset/. However, I found using the build-in bitset is slower than directly operating on an int in another question.


Log in to reply
 

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