9ms C++


  • 0
    L
    
    void proceed(vector<vector<int>>& output, vector<int>& cur, vector<int>& nums, int i) {
        if (i >= nums.size()) return;
    
        for (; i < nums.size(); ++i) {
            int n = nums[i];
            if (i + 1 < nums.size() && nums[i] == nums[i + 1]) {
                int duplicates = 1;
                i++;
                while (i < nums.size() && nums[i] == nums[i - 1]) {
                    duplicates++;
                    i++;
                }
                i--;
                for (int j = 0; j < duplicates; j++) {
                    cur.push_back(n);
                    output.push_back(cur);
                    proceed(output, cur, nums, i + 1);
                }
                for (int j = 0; j < duplicates; j++) {
                    cur.pop_back();
                }
            }
            else {
                cur.push_back(n);
                output.push_back(cur);
                proceed(output, cur, nums, i + 1);
                cur.pop_back();
            }
    
        }
    }
    
    vector<vector<int>> subsetsWithDup(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> output;
        vector<int> cur;
        output.push_back(cur);
        proceed(output, cur, nums, 0);
        return output;
    }
    

Log in to reply
 

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