Simple solution using Backtracking!


  • 1
    M

    For every element it has two options:

    1. Either it is in set.
    2. or it is NOT in set.
      I used this concept to write this code.
    class Solution {
    public:
        vector<vector<int> > res;
        
        void findsub(vector<int> &s, vector<int> &v, int i)
        {
            if(i==s.size())
            {
                res.push_back(v);
                return;
            }
            
            findsub(s, v, i+1);
            
            v.push_back(s[i]);
            findsub(s, v, i+1);
            
            v.pop_back();   //backtrack
            return;
            
        }
        vector<vector<int> > subsets(vector<int> &S) {
            
            sort(S.begin(), S.end());
            vector<int> v;
            findsub(S,v, 0);
            return res;
            
        }
    };

Log in to reply
 

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