dynamic programming approach of fibonacci series

pull/1167/head
TaHaSyedKhan 2023-03-17 04:26:19 +05:30
parent af47764be0
commit df8a479ba0
2 changed files with 32 additions and 0 deletions

View File

@ -7,6 +7,8 @@ require('./linked-lists/singly');
// Maths
require('./maths/fibonacci-series');
require('./maths/dynamic-fibonacci-series');
// Recursion
require('./recursion/factorial');

View File

@ -0,0 +1,30 @@
// dynamic programming approach of fibonacci series
// time complexity: O(n)
function dynamicFibonacci() {
let cache = {};
// here is the concept of closure in javaScript
const fib = (n) => {
// check if already calculated for n
if (n in cache) {
return cache[n];
} else if (n < 2) { // base case
return n;
} else {
// store result in cache
cache[n] = fib(n - 1) + fib(n - 2);
return cache[n];
}
}
console.log(fib(10));
}
dynamicFibonacci();
// output: 55