Created
January 17, 2021 02:03
-
-
Save diogojorgebasso/2f56522c537d9f0ee83b7f56a3da5f1f to your computer and use it in GitHub Desktop.
Doing the same Fibonacci operation, with very different performance
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
//easy to visualize and code, but... | |
function fib(n) { | |
if (n <= 1) return 1; | |
return fib(n - 1) + fib(n - 2); | |
} | |
//very time-consuming. | |
//SOLUTION | |
//using memoization | |
function fib(n) { | |
if (n in memo) return memo[n]; | |
if (n <= 1) return 1; | |
memo[n] = fib(n - 1) + fib(n - 2); | |
return memo[n]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment