111. Climbing Stairs
Description
假设你正在爬楼梯,需要n步你才能到达顶部。但每次你只能爬一步或者两步,你能有多少种不同的方法爬到楼顶部?
Example 1:
Input: n = 3
Output: 3
Explanation:
1) 1, 1, 1
2) 1, 2
3) 2, 1
total 3.
Example 2:
Input: n = 1
Output: 1
Explanation:
only 1 way.
分析:该题为上楼梯问题,要求的是到达某一台阶的方法数,由于上楼方式有走一个台阶和走两个台阶两种方式,故我们很容易推出递推关系:
result[n]=result[n-1]+result[n-2]
因此我们初始化result[0]=0,result[1]=1,result[2]=2即可开始遍历
代码如下:python3
class Solution:
"""
@param n: An integer
@return: An integer
"""
def climbStairs(self, n):
# write your code here
if n <= 2:
return n
result=[1,2]
for i in range(n-2):
result.append(result[-2]+result[-1])
return result[-1]
相关习题:
leecode 1054. Min Cost Climbing Stairs