Last active
August 22, 2017 17:21
-
-
Save fed/4fe059336d58fe22827931c5d1d6af66 to your computer and use it in GitHub Desktop.
Fibonacci with Memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Time complexity: O(n) | |
// Space complexity: O(n) | |
const memo = new Map(); | |
function fibonacci(n) { | |
if (memo.has(n)) { | |
return memo.get(n); | |
} | |
if (n <= 1) { | |
return 1; | |
} | |
const result = fibonacci(n - 1) + fibonacci(n - 2); | |
memo.set(n, result); | |
return result; | |
} | |
const array = []; | |
for (let i = 0; i < 10; i++) { | |
array.push(fibonacci(i)); | |
} | |
console.log(array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment