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], [] ]Array Backtracking
class Solution {
public:
vector<vector<int>> res;
void function(int start,int len,vector<int> S, vector<int> tmp)
{
if(tmp.size()==len)
res.push_back(tmp);
else{
for(int i=start;i<=S.size()-(len-tmp.size());i++)
{
if(i>start&&S[i]==S[i-1])//跳过重复的元素
continue;
vector<int> v(tmp);
v.push_back(S[i]);
function(i+1,len,S,v);
}
}
}
vector<vector<int> > subsetsWithDup(vector<int> &S) {
if(S.size()<0)
return res;
else if(S.size()==0)
{
vector<int> tmp;
res.push_back(tmp);
return res;
}
else{
sort(S.begin(),S.end());//排序
vector<int> tmp;
res.push_back(tmp);
for(int len=1;len<=S.size();len++)
function(0,len,S,tmp);
return res;
}
}
};