Created
January 24, 2019 19:36
-
-
Save yanil3500/358ab9b878d9c9e3fe30683f4906d433 to your computer and use it in GitHub Desktop.
Memoized Fibonacci
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 fibonacci(n: Int) -> Int { | |
var numbers = [Int:Int]() | |
return fibHelper(n: n, nums: &numbers) | |
} | |
func fibHelper(n: Int, nums: inout [Int:Int]) -> Int { | |
if let result = nums[n] { | |
return result; | |
} else if n == 1 { | |
nums[n] = 0 | |
return 0 | |
} else if n == 2 { | |
nums[n] = 1 | |
return 1 | |
} else { | |
nums[n] = fibHelper(n: n - 1, nums: &nums) + fibHelper(n: n - 2, nums: &nums) | |
} | |
return nums[n]! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment