题目描述
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], [] ]
对于递归的解法,根据之前 Subsets 子集合 里的构建树的方法,在处理到第二个2时,由于前面已经处理了一次2,这次我们只在添加过2的[2] 和 [1 2]后面添加2,其他的都不添加,那么这样构成的二叉树如下图所示:
[] / \ / \ / \ [1] [] / \ / \ / \ / \ [1 2] [1] [2] [] / \ / \ / \ / \ [1 2 2] [1 2] X [1] [2 2] [2] X []
代码只需在原有的基础上增加一句话,while (S[i] == S[i + 1]) ++i; 这句话的作用是跳过树中为X的叶节点,因为它们是重复的子集,应被抛弃。代码如下:
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int> &S) {
if (S.empty()) return {};
vector<vector<int>> res;
vector<int> out;
sort(S.begin(), S.end());
getSubsets(S, 0, out, res);
return res;
}
void getSubsets(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]);
getSubsets(S, i + 1, out, res);
out.pop_back();
while (i + 1 < S.size() && S[i] == S[i + 1]) ++i;
}
}
};
转自:
http://www.cnblogs.com/grandyang/p/4310964.html