I made two mistakes in this problem.
1.I forget to push_back the cur to answer when the cur.size() == num.
2.the change from this problem to subsets is just we need to write a judgement that in the same layer of the num, if S[i] == S[i-1] ,we just ignore the S[i].because this cause the duplicates. however,when I finished the judgement, I forget to write continue to make this judgement take effect.
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int>> answer;
vector<int> cur;
answer.push_back(cur);
if(S.empty())
return answer;
sort(S.begin(),S.end());
for(int i = 1;i<=S.size();i++)
dfs(0,i,S,cur,answer);
return answer;
}
void dfs(int start,int num,vector<int> &S,vector<int> &cur,vector<vector<int>> &answer)
{
if(cur.size() == num)
{
answer.push_back(cur);
return;
}
for(int i = start;i<S.size();i++)
{
if(i!= start && S[i] == S[i-1])
continue;
cur.push_back(S[i]);
dfs(i+1,num,S,cur,answer);
cur.pop_back();
}
}
};