Share my C++ solution


  • 0
    V
    class Solution {
    public:
        vector<vector<int>> subsetsWithDup(vector<int>& nums) {
            int n = nums.size();
            vector<vector<int>> ret;
            
            if (n == 0)
                return ret;
            
            sort(nums.begin(), nums.end());
            
            int i = 0, j = 0, len = 0, t = 0;
            vector<int> temp;
            ret.push_back(temp);
            
            while (i < n)
            {
                len = t = ret.size();
                for (j = 0; j < len; j++)
                {
                    temp = ret[j];
                    temp.push_back(nums[i]);
                    ret.push_back(temp);
                }
                
                if (i+1 < n && nums[i+1] == nums[i])
                {
                    while (i+1 < n && nums[i+1] == nums[i])
                    {
                        len = ret.size();
                        for (j = len - t; j < len; j++)
                        {
                            temp = ret[j];
                            temp.push_back(nums[i+1]);
                            ret.push_back(temp);
                        }
                        i++;
                    }
                }
                i++;
            }
            
            return ret;
        }
    };

Log in to reply
 

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