Created
December 6, 2021 09:51
-
-
Save haase1020/c025a7abfae1271223e9bceadc120caa to your computer and use it in GitHub Desktop.
fibonacci recursive
This file contains hidden or 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
// multiple recursion: one than one recursive call per iteration | |
// time complexity: O(2^n) or exponential time | |
// space complexity: O(n) | |
function fibonacci(n) { | |
if ((n === 1) | (n === 2)) return 1; | |
return fibonacci(n - 1) + fibonacci(n - 2); // multiple calls of fibonacci | |
} | |
// better but still slower than iterative | |
function fibonacciMemoized(n, cache = []) { | |
if (n === 0) return 0; | |
if (n === 1) return 1; | |
if (cache[n]) return cache[n]; | |
cache[n] = fibonacciMemoized(n - 2, cache) + fibonacciMemoized(n - 1, cache); // multiple calls of fibonacci | |
return cache[n]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment