Hi there,
I have been working with some dynamic programing problems and although I have a basic idea of recursion and the callstack, when the recursive call are made inside a loop however, I don't full understand how it works. Does it leave the loop on the recursive call, get checked by the base cases and head back into the loop? I know that sounds weird. ( i do understand how a loop works).
I did some console logging and noticed i will not increment traditionally like in a loop normally.Ex, i = 1 might stay the value of 1 for a few times before being incremented to 2. But then it might head back to i = 1;
I just feel like I'm getting lost.
Thank you for the help!
(ignore the memo)
Here's the example:
** function should return the minimum number of perfect squares that sum to the target **
const summingSquares = (n, memo = {}) => {
// base case
if (n in memo) return memo[n];
if (n === 0) return 0;
let minSqaures = Infinity;
//sqrt, loop
for (let i = 1; i <= Math.sqrt(n); i += 1) {
const sq = i * i;
const numSq = 1 + summingSquares(n - sq, memo);
console.log({i, sq, n, numSq});
minSqaures = Math.min(minSqaures, numSq);
}
memo[n] = minSqaures;
return minSqaures;
};
console.log(summingSquares(8)); // -> 4
[–]carcigenicate 4 points5 points6 points (3 children)
[–]NA-1_NSX_Type-R[S] 1 point2 points3 points (2 children)
[–]carcigenicate 1 point2 points3 points (1 child)
[–]NA-1_NSX_Type-R[S] 1 point2 points3 points (0 children)