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) {
sort(S.begin(), S.end());
vector<vector<int> > res;
vector<int> path;
dfs(S, 0, path, res);
return res;
}
void dfs(const vector<int> &s, int start, vector<int> &path, vector<vector<int> > &res) {
if (start == s.size()) {
res.push_back(path);
return ;
}
int prev = s[start]+1;
for (int i = start; i < s.size(); i++) {
if (prev == s[i]) {
continue;
}
prev = s[i];
path.push_back(s[i]);
dfs(s, i+1, path, res);
path.pop_back();
}
res.push_back(path);
return ;
}
};
本文介绍了一种解决含重复元素集合的所有可能子集问题的算法。通过先排序再使用深度优先搜索(DFS)的方法,确保了子集内元素的非递减顺序且不包含重复的子集。该算法适用于计算机科学中的组合生成问题。

被折叠的 条评论
为什么被折叠?



