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:

这道题是求子集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++;
        }
    }
};

你可能感兴趣的:(LeetCode90:Subsets II)