Subsets II

题目:

 

Given a collection of integers that might contain duplicates, 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,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

代码如下:

   void getsubset(set<vector<int> > &subsets,vector<int> &S,int i)
    {
        vector<int> tmp;
        for(int j=0;j<S.size();j++)
        {
            if(i&(1<<j))tmp.push_back(S[j]);
        }
        subsets.insert(tmp);
    }
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        set<vector<int> > subsets;
        set<vector<int> >::iterator j;
        vector<vector<int> > result;
        sort(S.begin(),S.end());
        int n=S.size();
        for(int i=0;i<1<<n;i++)
        {
            getsubset(subsets,S,i);
        }
        for(j=subsets.begin();j!=subsets.end();j++)
        {
            result.push_back(*j);
        }
        return result;
    }

 

posted @ 2013-05-29 20:02  javawebsoa  Views(314)  Comments(0Edit  收藏  举报