Mental Model
Remember past Fibonacci numbers so you don't calculate them again.
Analogy: Like writing down answers on a notebook so you don't solve the same math problem twice.
fib[0] = 0 fib[1] = 1 fib[2] = ? fib[3] = ? fib[4] = ? ...
fib[0] = 0 fib[1] = 1 fib[2] = ? fib[3] = ? fib[4] = ? ...
fib = [0, 1, ?, ?, ?, ?]
fib = [0, 1, 1, ?, ?, ?]
fib = [0, 1, 1, 2, ?, ?]
fib = [0, 1, 1, 2, 3, ?]
fib = [0, 1, 1, 2, 3, 5]
fib = [0, 1, 1, 2, 3, 5] Answer: 5
class FibonacciDP { constructor() { this.fib = []; } calculate(n) { if (n === 0) return 0; if (n === 1) return 1; this.fib[0] = 0; // base case this.fib[1] = 1; // base case for (let i = 2; i <= n; i++) { this.fib[i] = this.fib[i - 1] + this.fib[i - 2]; // build fib[i] from previous two } return this.fib[n]; // return nth Fibonacci number } } const fibCalc = new FibonacciDP(); const n = 5; const result = fibCalc.calculate(n); console.log(`Fibonacci number for n=${n} is ${result}`);
if (n === 0) return 0;if (n === 1) return 1;this.fib[0] = 0; // base casethis.fib[1] = 1; // base casefor (let i = 2; i <= n; i++) {this.fib[i] = this.fib[i - 1] + this.fib[i - 2];return this.fib[n];if (n === 0) return 0;
if (n === 1) return 1;
for (let i = 2; i <= n; i++) {
function fibDP(n) {
const fib = [0, 1];
for (let i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
console.log(fibDP(6));function fibDP(n) {
const fib = [0, 1];
for (let i = 1; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}fibDP(0) and fibDP(1)? How does the function handle these edge cases?function fibDP(n) {
if (n <= 1) return n;
const fib = new Array(n + 1).fill(0);
fib[1] = 1;
for (let i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}Pass the test and this pattern moves unknown