LeetCode题目地址
假设你正在爬楼梯,需要n步你才能到达顶部。但每次你只能爬一步或者两步,你能有多少种不同的方法爬到楼顶部?
def climbStairs(self, n):
# write your code here
if n <= 0:
return 0
f = [0] * n
f[0] = 1
if n > 1:
f[1] = 2
for i in range(2,n):
f[i] = f[i-1]+f[i-2]
return f[n-1]
动态规划
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
first = 1
sec = 2
for i in range(2,n):
temp = first + sec
first = sec
sec = temp
return sec