Monday, November 25, 2013

LeetCode Problem : Subsets

Problem


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],
  []
]

Code


vector<vector<int> > subsets(vector<int> &S) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    sort(S.begin(),S.end());
    int n = S.size();   
    int num = 1 << n;
    vector<vector<int> > result;
    for(int i = 0; i< num; ++i){
        vector<int> tmp;
        for(int pos = 0;pos < n; ++pos){
            if(i & (1 << pos))
                tmp.push_back(S[pos]);
        }
        result.push_back(tmp);
    }
    return result;
}

No comments:

Post a Comment