给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/subsets-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums)
{
vector<vector<int>> ret;
vector<int> tmp;
sort(nums.begin(), nums.end());
backtrack(ret, tmp, nums, 0);
return ret;
}
void backtrack(vector<vector<int>>& ret, vector<int> &tempList, vector<int>& nums, int start)
{
int j = 0;
for(j = 0; j < ret.size(); j++)
{
if(tempList == ret[j])
break;
}
if(j == ret.size())
ret.push_back(tempList);
for(int i = start; i < nums.size(); i++)
{
tempList.push_back(nums[i]);
backtrack(ret, tempList, nums, i+1);
tempList.erase(tempList.begin() + tempList.size() - 1);
}
}
};