# 子集 II

给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。

 

示例 1:

输入:nums = [1,2,2]
输出:
[[],[1],[1,2],[1,2,2],[2],[2,2]]

示例 2:

输入:nums = [0]
输出:
[[],[0]]

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; vector> res; vector nums = {1, 2, 2}; res = sol.subsetsWithDup(nums); for (auto i : res) { for (auto j : i) cout << j << " "; cout << endl; } return 0; } ``` ## 答案 ```cpp class Solution { public: vector> result; vector> subsetsWithDup(vector &nums) { sort(nums.begin(), nums.end()); vector temp; result.push_back(temp); getAns(0, nums, result, temp); return result; } void getAns(int start, vector &nums, vector> &result, vector temp) { if (start == nums.size() - 1) { temp.push_back(nums[start]); result.push_back(temp); } else { for (int i = start; i < nums.size(); i++) { while (i != 0 && i != start && nums[i] == nums[i - 1]) { i++; } if (i == nums.size()) break; temp.push_back(nums[i]); result.push_back(temp); getAns(i, nums, result, temp); temp.pop_back(); } } } }; ``` ## 选项 ### A ```cpp class Solution { public: vector> subsetsWithDup(vector &nums) { sort(nums.begin(), nums.end()); vector> res; vector cur; for (int i = 0; i <= nums.size(); i++) { dfs(res, cur, nums, 0, i); } return res; } void dfs(vector> &res, vector &cur, vector &nums, int begin, int n) { if (cur.size() == n) { res.push_back(cur); return; } for (int i = begin; i < nums.size(); i++) { if (i > begin && nums[i] == nums[i - 1]) continue; cur.push_back(nums[i]); dfs(res, cur, nums, i + 1, n); cur.pop_back(); } return; } }; ``` ### B ```cpp class Solution { public: vector> ans; vector cur; vector v; void dfs(int depth) { ans.push_back(cur); if (depth == v.size()) return; for (int i = depth; i < v.size(); ++i) { if (i > depth && v[i] == v[i - 1]) continue; cur.push_back(v[i]); dfs(i + 1); cur.pop_back(); } } vector> subsetsWithDup(vector &nums) { sort(nums.begin(), nums.end()); v = nums; dfs(0); return ans; } }; ``` ### C ```cpp class Solution { public: vector> subsetsWithDup(vector &nums) { vector> result; vector item; set> rset; result.push_back(item); sort(nums.begin(), nums.end()); CreatSet(0, result, item, nums, rset); return result; } void CreatSet(int i, vector> &result, vector &item, vector &nums, set> &rset) { if (i >= nums.size()) return; item.push_back(nums[i]); if (rset.find(item) == rset.end()) { rset.insert(item); result.push_back(item); } CreatSet(i + 1, result, item, nums, rset); item.pop_back(); CreatSet(i + 1, result, item, nums, rset); } }; ```