C++ recursive solution, maybe easy to understand;


  • 0
    Z

    The idea is to make sure that every tmp.push_back(S[i]) can make a new subset, and then push it in the res.

    void helper(vector<int> tmp,vector<vector<int>> &res,vector<int> &S, int start){
        res.push_back(tmp);
    
        int n=S.size();
    
        for(int i=start;i<n;i++){
            if(i>start&&S[i]==S[i-1])continue;//skip the duplicate element
    
            tmp.push_back(S[i]);
            helper(tmp,res,S,i+1);
            tmp.pop_back();
        }
    }
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<vector<int>> res;
        vector<int> tmp;
        sort(S.begin(),S.end());
    
        helper(tmp,res,S,0);
    
        return res;
    }`

Log in to reply
 

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