Turn around the situation
The final step is to make our solution iterative. With the previous (top-down) solution, we started with n and then repeatedly broke it down into smaller and smaller values until we reached n == 0
and n == 1
. Instead, we will start with the base case and work our way up.
xxxxxxxxxx
15
function fib(n) {
if (n === 0) return 0;
​
// initialize cache
let cache = new Array(n + 1).fill(0);
cache[1] = 1;
​
// iteratively fill cache
for (let i = 2; i <= n; i++) {
cache[i] = cache[i - 1] + cache[i - 2];
}
return cache[n];
}
​
console.log(fib(5));
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment