本道题题目要求如下:
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 I的解法:
画张图说明我的思路
2‘跟2没有什么实质区别,只是index不同。
就是按上图来做dfs遍历,root到任意节点的组合都是一种subset,但是需要注意的是,在每次插入到res前需要检测res是不是有了这个元素,如果有了则跳出这层recursive function。
其实这题在leetcode discussion上面有更好的解法,用iteration解决的。。但是我用的这种解法更接近我对backtracking的理解。所以就用了这个,而且这是我第一遍做leetcode,基本只求方法对,不求方法最优。
我的代码如下:
class Solution {
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
vector<int> tmp;
sort(S.begin(), S.end());
dfs(S, tmp, 0, S.size()-1);
return res;
}
private:
vector<vector<int>> res;
void dfs(vector<int>& S, vector<int> &tmp, int start, int end) {
if (find(res.begin(), res.end(), tmp) != res.end())
return;
else
res.push_back(tmp);
for (int index = start; index <= end; ++index) {
tmp.push_back(S[index]);
dfs(S, tmp, index+1, end);
tmp.pop_back();
}
}
};