Subsets II

Description

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

Solutions

My solution

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        vector<vector<int>> subsets(1);
        unordered_map<int, int> freqs;
        for(int num : nums)
            ++freqs[num];
        for(auto p : freqs){
            int size = subsets.size();
            for(int i = 0; i < size; ++i){
                auto v = subsets[i];
                for(int j = 0; j < p.second; ++j){
                    // use j+1 p.first;
                    v.push_back(p.first);
                    subsets.push_back(v);
                }
            }
        }
        return subsets;
    }
};

Another iterative solution

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        vector<vector<int>> subsets(1);
        sort(nums.begin(), nums.end());
        int size = 0;
        for(int i = 0; i < nums.size(); ++i){
            int start = (i == 0 || nums[i] != nums[i - 1]) ? 0 : size;
            size = subsets.size();
            for(int j = start; j < size; ++j){
                auto v = subsets[j];
                v.push_back(nums[i]);
                subsets.push_back(v);
            }
        }
        return subsets;
    }
};

Recursive solution

class Solution {
public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<int> acc;
        vector<vector<int>> subsets;
        dfs(nums, 0, acc, subsets);
        return subsets;
    }
    
    void dfs(vector<int> &nums, int begin, vector<int> &acc, vector<vector<int>> &subsets){
        subsets.push_back(acc);
        for(int i = begin; i < nums.size(); ++i){
            if(i == begin || nums[i] != nums[i - 1]){
                acc.push_back(nums[i]);
                dfs(nums, i + 1, acc, subsets);
                acc.pop_back();
            }
        }
    }
};

Last updated