【题目】
You are climbing a stair case. It takes nsteps to reach to the top.
Each time you can either climb 1 or 2steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
爬楼梯,一次可以爬一步或者两步。爬n层,问一共有多少种。
【思路】DP
如果n = 1层,可以有[1] , f(1) = 1种方法
如果n = 2层,可以有[1,1] ,[2], f(2) = 2种方法
如果n = 3层,可以有[1,1,1],[1,2],[2,1], f(3) = f(1) + f(2) = 3种方法。
如果n = 4层,可以有[1,1,1,1],[1,2,1],[1,1,2],[2,1,1],[2,2] , f(5) = f(4) + f(3) = 5种方法。
可以发现 f(n) = f(n-1) + f(n-2)
【Python实现】
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1 or n == 0:
return 1
i,stairs1,stairs2 = 2,1,1
#i = 2 表示从2层楼梯开始,stairs1staris2 分别是n - 2, n-1 层楼梯的结果,
while i <= n:
stairs1 = stairs1 + stairs2
if i == n:# n = 2 ,4时
print(stairs1)
return stairs1
i += 1
stairs2 = stairs1 + stairs2
if i == n:# n = 3 ,5时
print(stairs2)
return stairs2
i += 1
s = Solution()
s.climbStairs(4)