Sunday, April 21, 2013

Leetcode: Subsets in C++




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.
If S = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]


Iterative Solution:
vector<vector<int> > subsets(vector<int> &S) {
        vector<vector<int> > result(1);
        vector<int> tmp;
        sort(S.begin(),S.end());
        int k =0;
        for(int i=0;i<S.size();i++)
        {
            k = result.size()-1;
            while(k>=0)
            {
                tmp = result[k];
                tmp.push_back(S[i]);
                result.push_back(tmp);
                k--;
            }
        }
        return result;
    }

No comments:

Post a Comment