Skip to content

Instantly share code, notes, and snippets.

@yanil3500
Created January 24, 2019 19:36
Show Gist options
  • Save yanil3500/358ab9b878d9c9e3fe30683f4906d433 to your computer and use it in GitHub Desktop.
Save yanil3500/358ab9b878d9c9e3fe30683f4906d433 to your computer and use it in GitHub Desktop.
Memoized Fibonacci
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