Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
分析:
简单的爬楼梯问题,如果这算DP题的话,那这应该是我见过的最简单DP题了。令f[i]表示到第i个楼梯时不同的方案数,f[i] = f[i - 1] + f[i - 2]。
代码:
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
f = {}
f[0] = 0
f[1] = 1
f[2] = 2
i = 3
while i <= n:
f[i] = f[i - 1] + f[i - 2]
i += 1
return f[n]

本文介绍了一个经典的爬楼梯问题,通过动态规划的方法来求解不同步长到达楼顶的不同路径数量。使用Python实现,并给出了简洁的代码示例。
5460

被折叠的 条评论
为什么被折叠?



