Last active
February 5, 2019 07:48
-
-
Save stevencurtis/45e281df6d9bc27d7d459aad7e6e8de8 to your computer and use it in GitHub Desktop.
Fibonacci top down passing the cache
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
func fib (_ num: Int) -> Int { | |
var first = [0, 1] | |
return fib(num, &first) | |
} | |
func fib(_ num: Int, _ cache: inout [Int]) -> Int { | |
if (cache.count > num) { | |
return cache[num] | |
} | |
let fibNum = fib(num - 1, &cache) + fib(num - 2, &cache) | |
cache.append(fibNum) | |
return fibNum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment