yanil3500
1/24/2019 - 7:36 PM

Memoized Fibonacci

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]!
}