# 90. Subsets II

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) {
if (S.empty()) return {};
vector<vector<int>> res(1);
sort(S.begin(), S.end());
int size = 1, last = S[0];
for (int i = 0; i < S.size(); ++i) {
if (last != S[i]) {
last = S[i];
size = res.size();
}
int newSize = res.size();
for (int j = newSize - size; j < newSize; ++j) {
res.push_back(res[j]);
res.back().push_back(S[i]);
}
}
return res;
}
};
``````

[]
[1]
[2]
[1 2]
[2 2]
[1 2 2]

``````                        []
/          \
/            \
/              \
[1]                []
/       \           /    \
/         \         /      \
[1 2]       [1]       [2]     []
/     \     /   \     /   \    / \
[1 2 2] [1 2]  X   [1]  [2 2] [2] 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;
}
}
};
``````

[]
[1]
[1 2]
[1 2 2]
[2]
[2 2]

Subsets

https://leetcode.com/problems/subsets-ii/

https://leetcode.com/problems/subsets-ii/discuss/30137/Simple-iterative-solution

https://leetcode.com/problems/subsets-ii/discuss/30168/C%2B%2B-solution-and-explanation

https://leetcode.com/problems/subsets-ii/discuss/30164/Accepted-10ms-c%2B%2B-solution-use-backtracking-only-10-lines-easy-understand.

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation