19.2.23 [LeetCode 90] Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
题意
一个有重复元素的集合,求出所有不重复的子集
题解
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 void solve(vector<int>&nums, vector<vector<int>>&ans, vector<int>&now, int i) { 4 int n = nums.size(), _i = i; 5 for (; i < n; i++) { 6 if (i != _i && nums[i] == nums[i - 1])continue; 7 now.push_back(nums[i]); 8 ans.push_back(now); 9 solve(nums, ans, now, i + 1); 10 now.pop_back(); 11 } 12 } 13 vector<vector<int>> subsetsWithDup(vector<int>& nums) { 14 sort(nums.begin(), nums.end()); 15 vector<vector<int>>ans; vector<int>now; 16 ans.push_back(vector<int>()); 17 solve(nums, ans, now, 0); 18 return ans; 19 } 20 };
循环的时候注意一下跳过重复元素即可
注定失败的战争,也要拼尽全力去打赢它;
就算输,也要输得足够漂亮。