'Mistake in Dry running of finding subsets question in cpp

code for finding subsets


# include <iostream>
# include <vector>
using namespace std;
void solve(vector<int>nums, vector<int> output, int index, vector<vector<int>>& ans){
    // base case
    if(index>=nums.size()){
        ans.push_back(output);
        return ;
    }
    // exclude
    solve(nums,output,index+1,ans);
    // include
    int element=nums[index];
    output.push_back(element);
    solve(nums,output,index+1, ans);
}


# code
vector<vector<int> > Subsets(vector<int>& nums){
   vector<vector<int>> ans;
   vector<int> output;
   int index=0;
   solve(nums, output, index, ans);
   return ans;
}
int main(){
   int n,a;
    cin>>n;

    vector<vector<int>> ans;
    vector<int> num;
    cout<<"Enter the elements in nums : ";
    for(int i=0; i<n; i++){
     cin>>a;
      num.push_back(a);
    }
   ans=Subsets(num);
   cout<<" ans vector : ";
      cout<<"[";
   for(int i=0; i<ans.size(); i++){
        cout<<"[";
      for(int j=0; j<ans[i].size(); j++){
      cout<< ans[i][j]<<" ";
      }
cout<<"],"<<endl;
    }
    cout<<"]"<<endl;
    return 0;
}

#output

3
Enter the elements in nums : 1 2 3
 ans vector : [[],
[3 ],
[2 ],
[2 3 ],
[1 ],
[1 3 ],
[1 2 ],
[1 2 3 ],
]

doubt :

above code is giving the correct output but i am having problem in dry running part. since we passing ans and output vectors in the function argument it will retain the content from below recursive function calls which causes the duplicacy of elements(2) as shown during 8th function call. what am i doing wrong in dry running part?enter image description here

tried to dryrun but getting dplicacy of elements



Solution 1:[1]

The output parameter is passed by value, not by reference. This results in a copy being created. The local output variable in the "original" solve call remains untouched.

The parameter for the calls should therefore be

Call A

solve({1, 2, 3}, {}, 0, ...)

which calls

solve({1, 2, 3}, {}, 0, ...)

... a few more recursive calls ...

Now for call A the local output variable has not changes, since the called function received a different object(a copy).

Then 1 is added to the output vector, a copy is made and passed to the second recursive call for call A.

solve({1, 2, 3}, {1}, 0, ...)

Note: Since nums is the same for all calls, but a copy may be expensive, it would be preferred to pass it by reference to const. Applying const to the object will have the compiler enforce that your code does not modify (= use non-const member functions/operators) the vector:

void solve(vector<int> const& nums, vector<int> output, int index, vector<vector<int>>& ans) ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fabian