Converting JavaScript function to C++

  c#, dynamic-programming, javascript

I was working on a Dynamic Programming Problem and was able to code up a Javascript solution:

function howSum(targetSum,numbers,memo = {}){
    //if the targetSum key already in hashmap,return its value
    if(targetSum in memo) return memo[targetSum]; 

    if(targetSum == 0) return [];
    if(targetSum < 0) return null;

    for(let num of numbers){
        let aWay = howSum(targetSum-num,numbers,memo);
        if(aWay !== null){
            memo[targetSum] = [...aWay,num];
            return memo[targetSum];
        }
    }

    //no way to generate the targetSum using any elements of input array
    memo[targetSum] = null;
    return null;
}

Now I was thinking over how I could translate this into a CPP code.
I would have to use a reference to an unordered map for the memo object.

But how should I go about returning the empty array and null values as in the base condition?Should I return an array pointer and realloc it when inserting an element?Wouldnt that be a C way of programming it?
Also how should I go about passing the default parameter to the memo unordered map in C++?Currently I have overloaded the function which creates the memo unorderd map and passes its reference.

Any guidance will be appreciated as I can solve future questions.

Source: Ask Javascript Questions

LEAVE A COMMENT