题目:
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?
Note: Given n will be a positive integer.
斐波那契数列的变形题
方法一:性能39ms
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
dp = [1 for i in range(n + 1)]
for i in range(2, n + 1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
方法二:性能32ms
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
a = b = 1
for i in range(n-1):
a, b = a + b, a
return a
这个方法的时间复杂度和空间复杂度都大大减小了耶。