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], [] ]利用subset的情形,主要是如何去掉分支!
//实现一:以二叉树形式实现:需额外的空间,并减枝,去掉相邻重复字母,之前未选中的树枝。因为在相邻的字母里会重复出现!
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int> > num;
vector<int> result;
vector<bool> used_flag(S.size(),false);//借用额外的空间加以实现
sort(S.begin(),S.end());//必须先排序!
subsets(S,0,num,result,used_flag);
return num;
}
void subsets(vector<int> &S,int index,vector<vector<int> > &num,vector<int> &result,vector<bool> &used_flag)
{
if(index >= S.size())
{
num.push_back(result);
return;
}
else
{
//不选择
subsets(S,index+1,num,result,used_flag);
if(index >= 1&&S[index] == S[index - 1] && used_flag[index - 1] == false)return ;//去掉重复分支
//选择
result.push_back(S[index]);
used_flag[index] = true;//记录是否使用过!
subsets(S,index+1,num,result,used_flag);
result.pop_back();
used_flag[index] = false;
}
}
//实现二: 多叉树,分别以每个字母打头,枚举出各个字母打头出现的可能情况。依次递推
//此种去重的办法,只需去掉相邻字母衍生出来的分支,而分支即为 i != index 的情形。
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int> > num;
vector<int> result;
sort(S.begin(),S.end());//必须先排序!
subsets(S,0,num,result);
return num;
}
void subsets(vector<int> &S,int index,vector<vector<int> > &num,vector<int> &result)
{
num.push_back(result);//每次动作都加入
for(int i = index ;i < S.size();i++)
{
if(i != index && S[i] == S[i-1])continue ;//当为分支时忽略当前路径
//选择
result.push_back(S[i]);
subsets(S,i+1,num,result);
result.pop_back();//弹出!
}
}
以下也可以:已经AC
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int> > num;
vector<int> result;
sort(S.begin(),S.end());//必须先排序!
subsets(S,0,num,result);
return num;
}
void subsets(vector<int> &S,int index,vector<vector<int> > &num,vector<int> &result)
{
num.push_back(result);//每次动作都加入
for(int i = index ;i < S.size();i++)
{
//选择
result.push_back(S[i]);
subsets(S,i+1,num,result);
result.pop_back();//弹出!
while(S[i] == S[i+1]&&i < S.size())i++;//当为分支与前面重复时忽略当前路径(用于减枝!)
}
}