Search code examples
c++depth-first-searchbacktracking

Print the powerset


Why is the below code for printing the powerset of a set of integers, giving wrong answer? Actually, it is only printing empty set. What mistake am I making?

vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>>subset;
        vector<int>v;
        dfs(subset,0,nums,v);
        return subset;
    }
    void dfs(vector<vector<int>> subset, int index, vector<int>&nums, vector<int>&v){
        subset.push_back(v);
        for(int i=index;i<nums.size();i++)
        {
            v.push_back(nums[i]);
            dfs(subset,i+1,nums,v);
            v.pop_back();
        }
    }

Solution

  • You are passing subset by value to dfs function. Try pass it by reference or by address. Otherwise your subset will not be changed.

    void dfs(vector<vector<int>> & subset, ...)