题目描述:
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 vector<vector<int>> result; 5 if (nums.size() == 0) { 6 return result; 7 } 8 9 sort(nums.begin(), nums.end()); 10 vector<int> elem; 11 12 for (int i = 0; i <= nums.size(); ++i) { 13 subsets(nums, i, 0, result, elem); 14 } 15 16 return result; 17 } 18 private: 19 void subsets(const vector<int> &nums, int len, int cur, vector<vector<int>> &result, vector<int> &elem) { 20 if (elem.size() == len) { 21 result.push_back(elem); 22 return; 23 } 24 25 for (int i = cur; i < nums.size(); ++i) { 26 elem.push_back(nums[i]); 27 subsets(nums, len, i + 1, result, elem); 28 elem.pop_back(); 29 // 跳过重复的元素 30 for (int j = i + 1; j < nums.size(); ++j) { 31 if (nums[j] != nums[i]) { 32 break; 33 } 34 ++i; 35 } 36 } 37 } 38 };