Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
递归的写法,根据下图
[] / \ / \ / \ [1] [] / \ / \ / \ / \ [1 2] [1] [2] [] / \ / \ / \ / \ [1 2 2] [1 2] X [1] [2 2] [2] X []
每一层,对于S中的一个元素是否出现进行处理。
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<vector<int>> res;
vector<int> out;
sort(S.begin(),S.end());
getSubset(S,0,out,res);
return res;
}
void getSubset(vector<int> &S,int pos,vector<int> &out, vector<vector<int>> &res){
res.push_back(out);
for(int i=pos;i<S.size();i++){
out.push_back(S[i]);
getSubset(S,i+1,out,res);
out.pop_back();
while(S[i]==S[i+1]) i++;
}
}
};