My sample C++ code


  • 2
    Z

    vector<vector<int> > subsets(vector<int> &S) {
    vector<vector<int> > ret;
    vector<int> subset;

    for (int i = 0; i < (1 << S.size()); i++)
    {
    	subset.clear();
    	for (int j = 0; j < S.size(); j++)
    	{
    		if ((1 << j) & i)
    			subset.push_back(S[j]);
    	}
    	sort(subset.begin(), subset.end());
    	ret.push_back(subset);
    }
    
    return ret;
    

    }

    For example, the set S has four elements, so there are pow(2, 4) = 16 subsets. We can use bits to represent these subsets, which index can be represented by four bits, corresponding to the four elements.


  • 0
    Q

    Simple and easy to understand, a good Solution!


Log in to reply
 

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