Simple C++ solution


  • 0
    G
        void _subsetsWithDup(vector<int>& nums, int idx, vector<int> subset, vector<vector<int>>& all_subsets) {
            if (idx <= nums.size()) all_subsets.push_back(subset);
            for (int i = idx; i < nums.size(); i++) {
                if (i != idx && nums[i] == nums[i - 1]) continue;   // Important: If this element is same as previous
                                                                    // and it's not the first element in this call,
                                                                    // skip to avoid duplicates.
                subset.push_back(nums[i]);
                _subsetsWithDup(nums, i + 1, subset, all_subsets);
                subset.pop_back();
            }
        }
    public:
        vector<vector<int>> subsetsWithDup(vector<int>& nums) {
            vector<vector<int>> all_subsets;
            vector<int> subset;
            sort(nums.begin(), nums.end());                         // sort to be able to detect duplicates
            _subsetsWithDup(nums, 0 /* index in 'nums' */, subset, all_subsets);
            return all_subsets;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.