What is the equivalent C++ code for the JavaScript code

  c#, dynamic-programming, javascript

I have been learning Dynamic Programming in YouTube but the code explained in it is in JavaScript which I dont know. Can anyone give me equivalent cpp code please.
Given a number and array of numbers and have to find elements by adding which gives the targetSum

const howSum = (targetSum,numbers)=> {
   if (targetSum === 0) return [];
   if (targetSum<0) return null;
   for(let num of numbers)
   {
      const remainder = targetSum - num;
      const remainderResult = howSum(remainder, numbers);
      if(remainderResult !== null)
      {
          return [ ...remainderResult, num];
       }
    }
};
console.log(howSum(7,[2,3]));

The cpp code I have written

#include<bits/stdc++.h>
using namespace std;
vector<int> v1;
int howSum(int n,vector<int> v)
{
    if(n==0)
    {
        v1.push_back(n);
        return 1;
    }
    if(n<0)
    {
        v1.erase(v1.begin(),v1.end());
        return 0;
    }
    for(int i=0;i<n;i++)
    {
        int rem=n-v[i];
        if(howSum(rem,v))
        {
            v1.push_back(rem);
            return 1;
        }
    }
    return 0;
}

int main()
{
    howSum(7,{5,3,4,7});
    for(auto i:v1)
        cout<<i<<" "<<endl;
}

I know my code is not effecient and I am trying to improve myself.
Can anyone please help me
And any suggestions where and how to learn DSA and DP in Cpp will be helpful

Source: Ask Javascript Questions

LEAVE A COMMENT