Created
July 25, 2017 17:57
-
-
Save selfup/b06437fd05cd52f80902f1541d554f21 to your computer and use it in GitHub Desktop.
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
def fib(n) | |
return n if n < 2 | |
# ruby has implicit returns | |
# so no need to say return on the last line here | |
fib(n - 1) + fib(n - 2) | |
end | |
def memo_fib(n, cache = {}) | |
return n if n < 2 | |
# same return rule applies here | |
# we either return existing cache, or add a new key/value | |
cache[n] ||= fib(n - 1, cache) + fib(n - 2, cache) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment