LeetCode90:Subsets II

时间:2023-03-08 16:41:16
LeetCode90:Subsets II

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:

LeetCode90:Subsets II

这道题是求子集Subsets的更一般的情况,即给定的集合中存在反复的情况,能够使用Combination Sum II 同样的方法来消除反复元素。

做到如今发现好多题目都是触类旁通的了。

runtime:8ms

class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<int> path;
vector<vector<int>> result;
result.push_back(path);
sort(nums.begin(),nums.end());
helper(nums,0,path,result);
return result;
} void helper(vector<int> &nums,int pos,vector<int>& path,vector<vector<int>> &result)
{
if(pos==nums.size())
return ; for(int i=pos;i<nums.size();i++)
{
path.push_back(nums[i]);
result.push_back(path);
helper(nums,i+1,path,result);
path.pop_back();
while(nums[i]==nums[i+1]) i++;
}
}
};