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 =
If S =
[1,2,2]
, a solution is:[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Solution:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
sort(S.begin(),S.end());
vector<vector<int> > result(1);
vector<int> tmp;
int pre = S[0];
//our working range. if there are duplicated element. Program will only apply to last working range. which will generate non duplicated subset.
int range = 0;
int k = 0;
int p = 0;
for(int i=0;i<S.size();i++)
{
k = result.size()-1;
if(i>0&&S[i]==pre)
p = result.size()-range;
else
{
p = 0;
range = k+1;
}
while(p<=k)
{
tmp = result[p];
tmp.push_back(S[i]);
result.push_back(tmp);
p++;
}
pre = S[i];
}
return result;
}
No comments:
Post a Comment