Problem
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],
[]
]
Code
void swd_r(map<int,int>::const_iterator it,const map<int,int>& freq,int pos, vector<int>& out,vector<vector<int> >& result) { if(it == freq.end()){ result.push_back(vector<int>(out.begin(),out.begin() + pos)); return; } int num = it->first; int count = it->second; for(int j =count; j >= 0; --j){ int cpos = pos; for(int i = 0; i < j; ++i){ out[cpos] = num; ++cpos; } map<int,int>::const_iterator cit = it; swd_r(++cit,freq,cpos,out,result); } } vector<vector<int> > subsetsWithDup(vector<int> &S) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. map<int,int> freq; int n = S.size(); for(int i = 0;i< n;++i) ++freq[S[i]]; vector<vector<int> > result; map<int,int>::const_iterator it = freq.begin(); vector<int> out(n); swd_r(it,freq,0,out,result); return result; }
No comments:
Post a Comment