Could anyone please let me know why the following code in c++ doesn't work?
// count number of ways to construct a target string from a given set of strings
#include "bits/stdc++.h"
using namespace std;
int countConstruct(string target, vector < string > wordBank, map < string, int > memo = {})
{
if (memo.find(target) != memo.end())
return memo.at(target);
if (target == "")
return 1;
int totalCount = 0;
for (auto word: wordBank)
{
if (target.find(word) == 0)
{
auto suffix = target.substr(word.length(), target.length() - word.length());
int numWaysForRest = countConstruct(suffix, wordBank, memo);
totalCount += numWaysForRest;
}
}
memo[target] = totalCount;
return totalCount;
}
int main(int argc, char * argv[])
{
cout << boolalpha;
cout << countConstruct("abcdef", { "ab", "abc", "cd", "def", "abcd", "ef" }) << endl;
cout << countConstruct("skateboard", { "bo", "ska", "ate", "sk", "boar" }) << endl;
cout << countConstruct(
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
{ "e", "eee", "eeee", "eeeee", "eeeeee", "eeeeeee" })
<< endl;
return 0;
}
where as it JavaScript counterpart does:
// count number of ways the target string can be constructed from a given set of strings
const countConstruct = (target, wordBank, memo = {}) => {
if (target in memo) return memo[target];
if (target === '') return 1;
let totalCount = 0;
for (let word of wordBank) {
if (target.indexOf(word) === 0) {
const numWaysToRest = countConstruct(target.slice(word.length), wordBank, memo);
totalCount += numWaysToRest;
}
}
memo[target] = totalCount;
return totalCount;
}
console.log(countConstruct("abcdef", ["ab", "abc", "cd", "def", "abcd", "ef"]));
console.log(countConstruct("skateboard", ["bo", "ska", "ate", "sk", "boar"]));
console.log(countConstruct("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", ["e", "eee", "eeee", "eeeee", "eeeeee", "eeeeeee"]));
In the above C++ code if I make the "memo" variable static the program works. Can anyone tell me how to make the program work without making it static and through recursion only? What is internals behind these?