Subsets II
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], [] ]
方法一:迭代
1 class Solution { 2 public: 3 vector<vector<int>> subsetsWithDup(vector<int>& nums) { 4 sort(nums.begin(), nums.end()); 5 vector<int> v; 6 vector<vector<int>> res; 7 8 res.push_back(v); //empty set 9 10 std::size_t prev_size = 0; 11 for(std::size_t i=0;i<nums.size();i++) 12 { 13 std::size_t size = res.size(); 14 for(std::size_t j=0;j<size;j++) 15 { 16 if(i== 0 || nums[i] != nums[i-1] || j >= prev_size) 17 { 18 v.assign(res[j].begin(),res[j].end()); 19 v.push_back(nums[i]); 20 res.push_back(v); 21 } 22 } 23 prev_size = size; 24 } 25 return res; 26 } 27 };
方法二:递归
1 #include <vector> 2 #include <algorithm> 3 using std::vector; 4 5 class Solution { 6 public: 7 vector<vector<int>> subsetsWithDup(vector<int>& nums) { 8 sort(nums.begin(), nums.end()); 9 vector<int> v; 10 vector<vector<int>> res; 11 subsetsWithDupCore(res, 0, nums, v); 12 return res; 13 } 14 private: 15 void subsetsWithDupCore(vector<vector<int>>& res,int start,vector<int>& nums,vector<int>& v) 16 { 17 if(start == nums.size()) 18 { 19 res.push_back(v); 20 return; 21 } 22 if(v.size() == 0 || nums[start] != v[v.size()-1]) 23 { 24 subsetsWithDupCore(res, start+1, nums, v); 25 } 26 27 v.push_back(nums[start]); 28 subsetsWithDupCore(res, start+1, nums, v); 29 v.pop_back(); 30 } 31 };