Short 8ms C++ solution with recursion


  • 0
    D
    class Solution {
    public:
        void subsets_helper(vector<int>& s, int m, vector<int>* ans, vector<vector<int> >* res) {
            if (!ans->empty()) {
                res->emplace_back(*ans);
            }
            for (int i = m; i < s.size(); ++i) {
                ans->emplace_back(s[i]);
                subsets_helper(s, i + 1, ans, res);
                ans->pop_back();
            }
        }
    
        vector<vector<int> > subsets(vector<int> &S) {
            sort(S.begin(), S.end());
            vector<int> ans;
            vector<vector<int> > result;
            result.emplace_back(vector<int>{});
            subsets_helper(S, 0, &ans, &result);
            return result;
        }
    };

Log in to reply
 

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