90.Subsets II
给定一个数组,数组中有重复元素,求出这个数组的子集,空集也算子集。
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
思路:
因为有重复元素,所以先排序,在第78题Subsets的基础上,使用set去重即可,注意set不能插入空数组,最后将set转化为Vector<vector<int>> 容器,再插入空集即可。
class Solution { public: vector<vector<int>> subsetsWithDup(vector<int>& nums) { sort(nums.begin(), nums.end()); set<vector<int>> res; int n = nums.size(); for (int i = 1; i <= n; i++) { vector<int> tmp; subsetsWithDupDFS(nums, tmp, 0, i, res); } vector<vector<int>> ans(res.begin(), res.end()); ans.push_back({}); return ans; } void subsetsWithDupDFS(vector<int>& nums, vector<int>& tmp, int start, int k, set<vector<int>>& res) { if (tmp.size() == k) { res.insert(tmp); return; } for (int i = start; i < nums.size(); i++) { tmp.push_back(nums[i]); subsetsWithDupDFS(nums, tmp, i + 1, k, res); tmp.pop_back(); } } };
思考:要是不用set去重该怎么做呢?