Skip to content

Instantly share code, notes, and snippets.

@cristhianleonli
Last active March 28, 2018 13:51
Show Gist options
  • Save cristhianleonli/84118ff30591c93fbede2b30473af608 to your computer and use it in GitHub Desktop.
Save cristhianleonli/84118ff30591c93fbede2b30473af608 to your computer and use it in GitHub Desktop.
// recursively with redundant calculations
func fibo(n: Int) -> Int {
if n < 2 { return n }
return fibo(n: n - 1) + fibo(n: n - 2)
}
// with memoization
var memo = Dictionary<Int, Int>()
func fibMemo(_ n: Int) -> Int {
if let result = memo[n] { return result }
if n < 2 { return n }
let result = fibMemo(n - 1) + fibMemo(n - 2)
memo[n] = result
return result
}
let results = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in 0...11 {
assert(fibMemo(i) == results[i])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment