如果利用递归的话则会超时
利用备忘的方法
class Solution(object):
num_dict={}
def climbStairs(self, n):
if n <= 2:
return n
if n not in self.num_dict:
self.num_dict[n] = self.climbStairs(n-1)+self.climbStairs(n-2)
return self.num_dict[n]
利用数学的方法(fibonacci)
class Solution(object):
def climbStairs(self, n):
if n <= 2:
return n
all = 0
one = 2
two = 1
for i in range (2, n):
all = one + two
two = one
one = all
return all