-2
#include<iostream>
#include<map>
#include<vector>

using namespace std;

map<int, vector<int>> dp;
vector<int> howSum(int& target, vector<int>& nums, vector<int> temp){
    if (target == 0) return temp;
    if (target < 0) return {};
    if (dp.find(target) != dp.end()) return dp[target];

    for (int i=0;i<nums.size();i++){  
      dp[target]=howSum(target-nums[i],nums,temp.push_back(nums[i]));
      if (dp[target]!={}) {return dp[target];}
    }
    return {};
}

int main(){
    int n,target; cin>>n>>target; vector<int> nums(n);
    for (int i=0;i<n;i++) cin>>nums[i];

    vector<int> ans = howSum(target, nums, {});
    if (ans.size()>0){
         for(auto i:ans) cout<<i<<" ";
    }
}

And it said i wrong the line "dp[target] = howSum(target-nums[i], nums,temp.push_back(nums[i]));" And it said "expected primary-expression before ‘{’ token"

  • 2
    Post code as text not as image. – Jason Jan 21 '23 at 13:20
  • 6
    "_this code worked perfectly in Python but i don't know why it doesn't work in C++_": How does that make sense? It is complaining about a syntax error. What does code written in a different language possibly say about the syntax in another? – user17732522 Jan 21 '23 at 13:23
  • 1
    Error messages refer to an exact line number, so you know which line the error was on. Unfortunately, you left off the line number when you posted your picture. – abelenky Jan 21 '23 at 13:27
  • FYI, you should only attempt to run code that passes the build stage (compilation, linking) with zero warnings and zero errors. – Thomas Matthews Jan 21 '23 at 14:55

1 Answers1

0

The issue with this code is that you are using the push_back function of the vector class on the same vector passed as an argument to the howSum function.

Push_back function modifies the vector in place, so it changes the temp vector argument passed to the function, and when it returns, it returns the modified version of the temp vector, which is passed by reference to all the recursive calls. So, all the recursive calls are modifying the same vector and the last call's modified version is returned.

To fix this, you can create a new vector inside the for loop and pass that vector to the next recursive call

komto909
  • 187
  • 1
  • 10