剑指offer,swift-斐波那契数列

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39

    override func viewDidLoad() {
        super.viewDidLoad()
        print(method1(n: 20))
        print(method2(n: 20))
        print(method3(n: 20))
        print(method4(n: 20))
    }
    func method1(n : Int) -> Int {
        if n <= 1{
            return n
        }
        return method1(n: n - 1) + method1(n: n - 2)
    }
    func method2(n : Int) -> Int{
        if n == 0 || n == 1{
            return n
        }
        var arr = Array(repeating: -1, count: n + 1)
        arr[0] = 0
        arr[1] = 1
        for i in 2...n{
            arr[i] = arr[i - 1] + arr[i - 2]
        }
        
        return arr[n]
    }
    func method3(n : Int) -> Int{
        if n == 0 || n == 1{
            return n
        }
        var prePreVal = 0
        var preVal = 1
        var currentVal = 1
        for _ in 2...n{
            currentVal = prePreVal + preVal
            prePreVal = preVal
            preVal = currentVal
        }
        return currentVal
    }
    func method4(n : Int) -> Int{
        if n == 0 || n == 1{
            return n
        }
        var preVal = 0
        var sum = 1
        for _ in 2...n{
            sum = sum + preVal
            preVal = sum - preVal
        }
        return sum
    }

你可能感兴趣的:(剑指offer,swift-斐波那契数列)