首页 > 代码库 > Subsets II
Subsets II
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], [] ]
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S)
{
vector<int> keys;
vector<int> count;
//count pairs
for(int i=0;i<S.size();i++)
{
int j=0;
for(j=0;j<keys.size();j++)
if(keys[j]==S[i]) break;
if(j==keys.size())
{
keys.push_back(S[i]);
count.push_back(1);
}
else
{
count[j]++;
}
}
//sort pairs
for(int i=0;i<keys.size();i++)
for(int j=i+1;j<keys.size();j++)
if(keys[i]>keys[j])
{
int tmp=keys[i];
keys[i]=keys[j];
keys[j]=tmp;
tmp=count[i];
count[i]=count[j];
count[j]=tmp;
}
vector<int> v;
for(int i=0;i<keys.size();i++) v.push_back(0);
vector<vector<int>> result;
generate(result,keys,count,v,0);
return result;
}
void generate(vector<vector<int>>& result,vector<int>& keys,vector<int>& count,vector<int>& v,int dep)
{
//add in the result
if(dep==keys.size())
{
vector<int> newv;
for(int i=0;i<dep;i++)
for(int j=0;j<v[i];j++)
newv.push_back(keys[i]);
result.push_back(newv);
return;
}
//generate with next key
for(int i=0;i<=count[dep];i++)
{
v[dep]=i;
generate(result,keys,count,v,dep+1);
}
}
};
public:
vector<vector<int> > subsetsWithDup(vector<int> &S)
{
vector<int> keys;
vector<int> count;
//count pairs
for(int i=0;i<S.size();i++)
{
int j=0;
for(j=0;j<keys.size();j++)
if(keys[j]==S[i]) break;
if(j==keys.size())
{
keys.push_back(S[i]);
count.push_back(1);
}
else
{
count[j]++;
}
}
//sort pairs
for(int i=0;i<keys.size();i++)
for(int j=i+1;j<keys.size();j++)
if(keys[i]>keys[j])
{
int tmp=keys[i];
keys[i]=keys[j];
keys[j]=tmp;
tmp=count[i];
count[i]=count[j];
count[j]=tmp;
}
vector<int> v;
for(int i=0;i<keys.size();i++) v.push_back(0);
vector<vector<int>> result;
generate(result,keys,count,v,0);
return result;
}
void generate(vector<vector<int>>& result,vector<int>& keys,vector<int>& count,vector<int>& v,int dep)
{
//add in the result
if(dep==keys.size())
{
vector<int> newv;
for(int i=0;i<dep;i++)
for(int j=0;j<v[i];j++)
newv.push_back(keys[i]);
result.push_back(newv);
return;
}
//generate with next key
for(int i=0;i<=count[dep];i++)
{
v[dep]=i;
generate(result,keys,count,v,dep+1);
}
}
};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。