题目
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: 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],
[]
]
分析
实现
/*
Author:Fancy
Date:2017-03-22
Algorithm:90-Subsets II
Time Complexity: O(n2)
*/
class Solution{
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
vector<int> tmp;
if (nums.empty())
return res;
sort(nums.begin(), nums.end());
dfs(res, tmp, nums, 0);
return res;
}
void dfs(vector<vector<int>>& res, vector<int>& tmp, vector<int>& nums, int index)
{
res.push_back(tmp);
//return;
for (int i = index; i < nums.size(); i++)
{
if (i != index&& nums[i] == nums[i - 1])
continue;
tmp.push_back(nums[i]);
dfs(res, tmp, nums, i + 1);
tmp.pop_back();
}
}
};