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], [] ]
解题思路:采用递归,分别得到对应长度的子数组的值,注意子数组要求不重复,可以用哈希来做;
#include<iostream>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
set<vector<int> >CompareSet;
//先输出SubsetLen长度的子串,然后确定索引为SubsetLen+1的值
void SubsetsRec(vector<int> &S,vector<int>tmp ,vector<vector<int>>&ResultSubset, int SubsetLen = 0, int Pos = 0)
{
vector<int> v;
for (int i = 0; i < SubsetLen;++i)
v.push_back(tmp[i]);
if (!CompareSet.count(v))//判别当前子数组是否重复
{
ResultSubset.push_back(v);
CompareSet.insert(v);
}
for (int i = Pos; i < S.size();++i)
{
tmp[SubsetLen] = S[i];//确定子数组中索引号为SubsetLen的值
SubsetsRec(S, tmp, ResultSubset, SubsetLen + 1, i + 1);
}
}
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int>>ResultSubset;
vector<int>SubsetTmp(S.size());
sort(S.begin(), S.end());
SubsetsRec(S,SubsetTmp ,ResultSubset);
return ResultSubset;
}