leetcode70爬楼梯

leetcode 70.爬楼梯
用斐波列那数列求解

class Solution:
    def climbStairs(self, n: int) -> int:
        if n == 0:
            return 0
        elif n ==1 :
            return 1
        else:
            a = 1
            b = 1
            for i in range(n-1):
                c = a
                a = a + b
                b = c
            return a

剩下两种方法:
在leetcode上看到的
作者:hialiens
链接:https://leetcode-cn.com/problems/climbing-stairs/solution/guan-fang-ti-jie-pythonshi-xian-by-hialiens/

import numpy as np
import math


class Solution:
    def climbStairs(self, n: int) -> int:

        # 斐波那契公式
        sqrt5 = math.sqrt(5)
        fibn = math.pow((1+sqrt5) / 2, n+1) - math.pow((1-sqrt5) / 2, n+1)
        return int(fibn // sqrt5)

        '''
        暴力法
        # 超时
        if n == 1:
            return 1
        if n == 2:
            return 2

        return self.climbStairs(n-1) + self.climbStairs(n-2)
        '''

        '''
        动态规划
        # 52 ms	13.6 MB
        if n == 1:
            return 1
        if n == 2:
            return 2
        dp = [1] + [2] + [False] * (n-2)
        # print(dp)
        for i in range(2, n):
            dp[i] = dp[i-1] + dp[i-2]
        return dp[-1]
        '''


    '''
        Binets 方法
        # 120 ms	28.8 MB
        q = np.mat([[1, 1], [1, 0]])
        res = self.matPow(q, n)
        return res.tolist()[0][0]

    def matPow(self, q, n):
        ret = np.mat([[1, 0], [0, 1]])
        while n:
            if n & 1 == 1:
                ret = np.dot(ret, q)
            n >>= 1
            q = np.dot(q, q)
        
        return ret
    '''

作者:hialiens
链接:https://leetcode-cn.com/problems/climbing-stairs/solution/guan-fang-ti-jie-pythonshi-xian-by-hialiens/

你可能感兴趣的:(leetcode,leetcode,算法)