My 10ms simple C++ code using bit manipulation


  • 0
    R
    vector<vector<int> > subsets(vector<int> &S) {
            vector<vector<int>> res;
            //res.push_back(NULL);
            if(S.size()==0) return res;
            int len = S.size();
            long num = pow(2,len);
            sort(S.begin(),S.end());
            for(long i = 0 ; i < num; i++){
                res.push_back(select(i,S));
            }
            return res;
            
        }
        vector<int> select(long m, vector<int> S){
            int i = 0;
            vector<int> res;
            
            while(i < S.size()){
                int j = m & 0x01;
                if(j == 1){
                    res.push_back(S[i]);
                }
                i ++ ;
                m = m >> 1;
            }
            return res;
        }
    

    The total amount of results is pow(2,S.size()), so a each bit represents for each number in S.


  • 0
    P
    This post is deleted!

Log in to reply
 

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