Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Subsets II

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

NOTE: Time and space complexity for this problem may be wrong

Brute Force


Optimized Recursive solution (backtracking)

class Solution {
private:
    void findSubsets(int ind, vector<int>& nums, vector<int>& res, vector<vector<int>>& ans)
    {
        ans.push_back(res); // push the empty subset;
        int n = nums.size();

        for (int i = ind; i < n; i++) {
            if (i != ind && nums[i] == nums[i - 1])
                continue; // handling duplicates
            res.push_back(nums[i]); // DO
            findSubsets(i + 1, nums, res, ans); // RECUR
            res.pop_back(); // UNDO/Backtrack
        }
    }

public:
    vector<vector<int>> subsetsWithDup(vector<int>& nums)
    {
        vector<vector<int>> ans;
        vector<int> res;

        sort(nums.begin(), nums.end());
        findSubsets(0, nums, res, ans);
        return ans;
    }
};