题目
代码
执行用时:32 ms, 在所有 Python3 提交中击败了76.04% 的用户
内存消耗:14.8 MB, 在所有 Python3 提交中击败了93.04% 的用户
通过测试用例:45 / 45
class Solution:
def deal(self,meno,n):
if n<=2:return n
if n in meno:
return meno[n]
a=self.deal(meno,n-1)
meno[n-1]=a
b=self.deal(meno,n-2)
meno[n-2]=b
return a+b
def climbStairs(self, n: int) -> int:
return self.deal(dict(),n)
【方法2】
执行用时:36 ms, 在所有 Python3 提交中击败了48.96% 的用户
内存消耗:14.8 MB, 在所有 Python3 提交中击败了93.60% 的用户
通过测试用例:45 / 45
class Solution:
def climbStairs(self, n: int) -> int:
if n<=2:return n
a,b=1,2
while n>1:
n-=1
a,b=b,a+b
return a
【方法3】binet’s formula
执行用时:28 ms, 在所有 Python3 提交中击败了92.37% 的用户
内存消耗:14.9 MB, 在所有 Python3 提交中击败了71.98% 的用户
通过测试用例:45 / 45
class Solution:
def climbStairs(self, n: int) -> int:
sqrt5 = 5**0.5
n+=1
fibN = ((1 + sqrt5) / 2) ** n - ((1 - sqrt5) / 2) ** n
return round(fibN / sqrt5)