Given a collection of integers that might contain duplicates, nums, 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 nums = [1,2,2]
, a solution
is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
Subscribe to see which companies asked this question
这题有重复元素,但本质上,跟上题很类似,也可以用类似的方法处理:
class Solution { public: vector<vector<int>> subsetsWithDup(vector<int>& nums) { vector<vector<int>> ans(1, vector<int>()); sort(nums.begin(), nums.end()); int pre_size = 0; for (int i = 0; i < nums.size(); i++) { int n = ans.size(); for (int j = 0; j < n; j++) //第二个for循环是为了求得包含nums[i]的所有子集 { if (i == 0 || nums[i] != nums[i -1] || j>=pre_size) { ans.push_back(ans[j]); //在尾部重新插入ans已经存在的子集 ans.back().push_back(nums[i]); //将nums[i]添加进去 } } pre_size = n; } return ans; } };
时间: 2024-10-14 10:51:19