Subsets

/*
Given a set of distinct integers, S, return all possible subsets.

Note:

Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
*/

class Solution {
public:

    void generate(vector<int> &S, int i, vector<vector<int> >& res)
    {
        if (i == S.size())
            return;
        
        int size = res.size();
        for (int j = 0; j < size ; ++j)
        {
            vector<int> aset = res[j];
            aset.push_back(S[i]);
            res.push_back(aset);
        }
        generate(S, i + 1, res);
    }
    
    vector<vector<int> > subsets(vector<int> &S) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        vector<vector<int> > res(1, vector<int>());
        
        sort(S.begin(), S.end());
        
        if (not S.empty()) generate(S, 0, res);
        
        return res;
    }
};
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s