递归,若当前元素不如栈,则后面与它相同的元素都不如栈
class Solution {
public:
void subset(vector<int>& nums,int sta,vector<vector<int>>& res,vector<int> ans)
{
if(sta>=nums.size())
{
res.push_back(ans);
return;
}
int i=sta+1;
if(sta+1<nums.size()&&nums[sta+1]==nums[sta])
{
while(i<nums.size()&&nums[i]==nums[i-1])
i++;
subset(nums,i,res,ans);
}
else
subset(nums,sta+1,res,ans);
ans.push_back(nums[sta]);
subset(nums,sta+1,res,ans);
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
vector<int> ans;
sort(nums.begin(),nums.end());
subset(nums,0,res,ans);
return res;
}
};
更加优雅的写法
class Solution {
public:
void subset(vector<int>& nums,int sta,vector<vector<int>>& res,vector<int>& ans)
{
res.push_back(ans);
for(int i=sta;i<nums.size();i++)
{
if(i==sta||nums[i]!=nums[i-1])
{
ans.push_back(nums[i]);
subset(nums,i+1,res,ans);
ans.pop_back();
}
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
vector<int> ans;
sort(nums.begin(),nums.end());
subset(nums,0,res,ans);
return res;
}
};