I was working on Combination Sum exercise and there is something that i wanted to do and i dont know if it’s possible and how to do it
-
How to add memoization ?
-
If memoization is not possible can i use child process to distribute the calculation and make it faster or is there another way ?
here is the code:
function countChange(money, coins) {
const result = [];
const memo = {};
function recurse(start, leftOver, selection) {
if (leftOver < 0) return;
if (leftOver === 0) {
result.push(selection);
return selection;
}
for (var i = start; i < coins.length; i++) {
recurse(i, leftOver - coins[i], selection.concat(coins[i]));
}
}
recurse(0, money, []);
console.log(result);
return result.length;
}
const long_result = countChange(999, [1, 2, 5, 10, 20, 50, 100]);
// const long_result = countChange(4, [1, 2]);
console.log(long_result);
I tried adding memoization but the results were not correct maybe i did not implemented it in the right way here is the code:
function countChange(money, coins) {
const result = [];
const memo = {};
function recurse(start, leftOver, selection) {
if (leftOver in memo) return memo[leftOver];
if (leftOver < 0) return;
if (leftOver === 0) {
result.push(selection);
// memo[leftOver] = selection;
return selection;
}
for (var i = start; i < coins.length; i++) {
memo[leftOver] = recurse(i, leftOver - coins[i], selection.concat(coins[i]));
}
}
recurse(0, money, []);
console.log(result);
return result.length;
}
// const long_result = countChange(999, [1, 2, 5, 10, 20, 50, 100]);
const long_result = countChange(4, [1, 2]);
console.log(long_result);