C++ 8 ms solution with explaination


  • 0
    H
    // Take [1,2,3] as example
    //         / - 2 - 3 - ]
    //  [  1 - | - 3 - ]
    //  [  2 - 3 - ]
    //  [  3 - ]
    vector<vector<int>> subsets(vector<int>& nums) {
        std::sort(nums.begin(), nums.end());
        vector<vector<int>> vv;
        vector<int> v;
        sub(vv, v, nums, 0, nums.size());
        return vv;
    }
    
    void sub(vector<vector<int>>& vv, vector<int>& v, vector<int>& nums, int start, int size) {
        vv.push_back(v);
        for (int i=start; i<size; ++i) {
            vector<int> vt = v;
            vt.push_back(nums[i]);
            sub(vv, vt, nums, i+1, size);
        }
    }

Log in to reply
 

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