假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1:
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1 阶
2. 2 阶
示例 2:
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1 阶
2. 1 阶 + 2 阶
3. 2 阶 + 1 阶
思路
第一个暴力递归,超时
增加@functools.lru_cache()记忆化搜索解决
优化使用dp,在121.买卖股票的最佳时机里学会了一点基本动态规划,用到这里
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
dp=[0]*(n+1)
dp[0]=dp[1]=1
for i in range(2,n+1):
dp[i]=dp[i-1]+dp[i-2]
return dp[-1]
还看到了更简的方法
# f(n)只依赖于f(n-1)和f(n-2),只需要两项就足够了
def climbStairs(self, n: int) -> int:
a = b = 1
for i in range(2, n + 1):
a, b = b, a + b
return b
作者:lu-nan-2
链接:https://leetcode-cn.com/problems/climbing-stairs/solution/zhi-xin-hua-shi-pa-lou-ti-zhi-cong-bao-l-lo1t/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。