My C++ recursive solution


  • 0
    A
    class Solution {
    public:
        void generate(vector<int> s, vector<int> v,vector<vector<int> >  &vt,int n)
        {
            if(n==s.size())
            {
                sort(v.begin(),v.end());
                vt.push_back(v);
                return;
            }
            if((n==0)||v.empty()||s[n]!=v.back())   //don't use duplicate item
            generate(s,v,vt,n+1);
            v.push_back(s[n]);
            generate(s,v,vt,n+1);
            
        }
    
        vector<vector<int> > subsetsWithDup(vector<int> &S) 
       {
            vector<vector<int> > vt;
            vector<int> v;
            sort(S.begin(),S.end());
            generate(S,v,vt,0);
            return vt;
        }
    };
    

    The idea is not to include duplicate item to generate the subset which doesn't include that item.


Log in to reply
 

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