遞歸解法:
class Solution:
def climbStairs(self, n: int) -> int:
cache = {}
return self.climb(n, cache)
def climb(self, n: int, cache):
#基本情況是0,1,2
if n == 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
elif n in cache:
return cache[n]
else:
cache[n] = self.climb(n - 2, cache) + self.climb(n - 1, cache)
return cache[n]
方法就是每次調用climb的n-2和n-1兩種情況,直到爲基本情況
斐波那契法:
n層的所有情況即爲n-1和n-2兩種,即,轉換爲斐波那契數列的計算:
class Solution:
def climbStairs(self, n: int) -> int:
result = [0,1,2]
len_re = 3
if n < len_re:
return result[n]
else:
for i in range(3, n + 1):
temp = result[-1] + result[-2]
result[-2] = result[-1]
result[-1] = temp
return result[-1]