Skip to content

Instantly share code, notes, and snippets.

@selfup
Created July 25, 2017 17:57
Show Gist options
  • Save selfup/b06437fd05cd52f80902f1541d554f21 to your computer and use it in GitHub Desktop.
Save selfup/b06437fd05cd52f80902f1541d554f21 to your computer and use it in GitHub Desktop.
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