这题其实跟斐波那契数列很像啦,都是num(n) = num(n - 1) + num(n -2),不过python并没有对尾递归做出优化,所以还是用的for循环来写的。代码如下;
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
if n == 2:
return 2
list1 = [1, 2]
for i in range(2, n):
list1.append(list1[i - 1] + list1[i - 2])
return list1[n - 1]