题目:
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], [] ]
思路:
思路1:递归,放与不放的问题。类似
http://blog.csdn.net/lanxu_yy/article/details/11885327,但需要考虑重复。 思路2:
在
http://blog.csdn.net/lanxu_yy/article/details/11885327
的基础上修改,完善针对重复数据的判断。
代码:
思路1:
class Solution {
public:
vector<vector<int> > v;
vector<vector<int> > subsetsWithDup(vector<int> &S) {
sort(S.begin(),S.end());
generate(vector<int>(), S, 0);
return v;
}
void generate(vector<int> res, vector<int> &S, int i)
{
if(i == S.size())
{
for(int i = 0; i < v.size(); i++)
{
if(v[i] == res)
{
return;
}
}
v.push_back(res);
return;
}
else
{
generate(res, S, i+1);
res.push_back(S[i]);
generate(res, S, i+1);
}
}
};
思路2:
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
sort(S.begin(),S.end());
vector<vector<int>> r;
vector<vector<int>> pre;
vector<vector<int>> cur;
int len=0;
vector<int> tmp;
cur.push_back(tmp);
do
{
pre = cur;
cur.clear();
for(int i=0;i<pre.size();i++)
{
r.push_back(pre[i]);
if(pre[i].size()>0)
{
int last=INT_MIN;
int duplicate = 0;
for(int j=0;j<S.size();j++)
{
if(S[j]<pre[i][0])
{
if(S[j]!=last)
{
vector<int> tmp = pre[i];
tmp.insert(tmp.begin(),S[j]);
cur.push_back(tmp);
duplicate = 0;
last=S[j];
}
}
else if(S[j]==pre[i][0])
{
int sum=0;
for(int k=0;k<pre[i].size();k++)
{
if(pre[i][k]==S[j])
{
sum++;
}
else
{
break;
}
}
duplicate++;
if(duplicate==sum+1)
{
vector<int> tmp = pre[i];
tmp.insert(tmp.begin(),S[j]);
cur.push_back(tmp);
break;
}
last=S[j];
}
else
{
break;
}
}
}
else
{
int last=INT_MIN;
for(int j=0;j<S.size();j++)
{
if(S[j]!=last)
{
vector<int> tmp = pre[i];
tmp.insert(tmp.begin(),S[j]);
cur.push_back(tmp);
}
last=S[j];
}
}
}
len++;
}while(len<=S.size());
return r;
}
};