509. 斐波那契数
题目链接:509. 斐波那契数
class Solution:
def fib(self, n: int) -> int:
if n==0:
return 0
dp=[0]*(n+1)
dp[0] = 0
dp[1] = 1
for i in range(2,n+1):
dp[i]=dp[i-1]+dp[i-2]
return dp[n]
70. 爬楼梯
题目链接:70. 爬楼梯
这题最重要的是写出递推公式,就是dp[i]=dp[i-1]+dp[i-2]
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n==1:
return 1
if n==2:
return 2
dp=[0]*(n+1)
dp[1]=1
dp[2]=2
for i in range(3,n+1):
dp[i]=dp[i-1]+dp[i-2]
return dp[i]
746. 使用最小花费爬楼梯
题目链接:746. 使用最小花费爬楼梯
使用dp[i] 记录每次最小花费值。
class Solution(object):
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
#total_cost=0
dp=[0]*(len(cost)+1)
for i in range(2,len(cost)+1):
dp[i]=min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2])
return dp[-1]