题目:
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], [] ]
代码:
class Solution {
public:
void backSubsets(vector<vector<int>>& res, vector<int>& nums, vector<int> cur, int idx, const int& length) {
if(idx == length)
return;
// cout << idx << ' ' << length << endl;
for(int i = idx; i<length; i++)
{
// if(i == idx || i == length - 1 || (i < length - 1 && nums[i] != nums[i+1]))
if(i == idx || i > idx && nums[i] != nums[i - 1])
{
cur.push_back(nums[i]);
res.push_back(cur);
backSubsets(res, nums, cur, i+1, length);
cur.pop_back();
}
}
return;
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
int length = nums.size();
vector<int> cur;
res.push_back(cur);
backSubsets(res, nums, cur, 0, length);
return res;
}
};