C++ 9ms clean solution


  • 0
    C
    • S(n) = S(n - 1) U (all set in S(n-1) append k), example for [1,2,3]
    • S(0) = [[]]
    • S(1) = [[]] U [[1]] = [[], [1]]
    • S(2) = [[], [1]] U [[2], [1,2]] = [[], [1], [2], [1,2]]
    • S(3) = [[], [1], [2], [1,2]] U [[3], [1,3], [2,3], [1,2,3]] = [[], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]]
    class Solution {
    public:
        void generate(vector<vector<int>> &sol, int k) {
            vector<vector<int>> temp = sol;
            for (int i = 0; i < temp.size(); ++i) {
                temp[i].push_back(k);
                sol.push_back(temp[i]);
            }
        }
    
        vector<vector<int>> subsets(vector<int>& nums) {
            vector<vector<int>> sol;
            sol.push_back(vector<int>());
            for (int i = 0; i < nums.size(); ++i) {
                generate(sol, nums[i]);
            }
            
            return sol;
        }
    };
    

Log in to reply
 

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