Skip to content

Instantly share code, notes, and snippets.

@fed
Last active August 22, 2017 17:21
Show Gist options
  • Save fed/4fe059336d58fe22827931c5d1d6af66 to your computer and use it in GitHub Desktop.
Save fed/4fe059336d58fe22827931c5d1d6af66 to your computer and use it in GitHub Desktop.
Fibonacci with Memoization
// 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