Share my concise recursive solution without for-loop


  • 0
    O
    class Solution {
    private:
        void dfs(vector<int>& nums, vector<int>& tmp, int index, int n, vector<vector<int>>& ans) {
            if (index == n) {
                ans.push_back(tmp);
                return;
            }
            tmp.push_back(nums[index]);
            dfs(nums, tmp, index + 1, n, ans);
            tmp.pop_back();
            dfs(nums, tmp, index + 1, n, ans);
        }
    public:
        vector<vector<int>> subsets(vector<int>& nums) {
            vector<int> tmp;
            vector<vector<int>> ans;
            dfs(nums, tmp, 0, nums.size(), ans);
            return ans;
        }
    };

Log in to reply
 

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