subset2

code

keypoint: 1)inside the dfs, using hash to ensure no same element will be pushed in twice.

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        vector<vector<int>> res;
        int n = nums.size();
        if(n == 0)
        {
            return res;
        }

        sort(nums.begin(), nums.end());
        vector<int> cur;
        dfs(res, nums, cur, 0);
        return res;
    }

    void dfs(vector<vector<int>>& res, vector<int>& nums, vector<int>& cur, int pos)
    {
        if(pos > nums.size())
        {
            return ;
        }

        res.push_back(cur);
        unordered_set<int> hash;

        for(int i = pos; i<nums.size(); i++)
        {
            if(hash.find(nums[i]) != hash.end())
            {
                continue;
            }
            cur.push_back(nums[i]);
            hash.insert(nums[i]);
            dfs(res, nums, cur, i+1);
            cur.pop_back();
        }
    }
};

results matching ""

    No results matching ""