509. 斐波那契数
视频:手把手带你入门动态规划 | 对应力扣(leetcode)题号:509.斐波那契数_哔哩哔哩_bilibili
class Solution(object):
def fib(self, n):
"""
:type n: int
:rtype: int
"""
# Corner Case
if n == 0:
return 0
# set up dp table
dp = [0] * (n + 1)
# intialize
dp[0] = 0
dp[1] = 1
# loop from the index 2 to n
for i in range(2, n + 1):
# recursion rule
dp[i] = dp[i - 1] + dp[i - 2]
# return
return dp[n]
70. 爬楼梯
视频:带你学透动态规划-爬楼梯(对应力扣70.爬楼梯)| 动态规划经典入门题目_哔哩哔哩_bilibili
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
#set up dp
dp=[0]*(n+1)
#as long as dp[1]=1 dp[2]=2
dp[0]=1
dp[1]=1
#loop for every step of dp
for i in range(2, n+1):
# the ith dp is the sum of i-1 and i-2 dp because both of which can
# reach to i in one or two steps
dp[i]=dp[i-2]+dp[i-1]
return dp[n]
746. 使用最小花费爬楼梯
视频讲解:动态规划开更了!| LeetCode:746. 使用最小花费爬楼梯_哔哩哔哩_bilibili
class Solution(object):
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
dp=[0]*(len(cost)+1)
for i in range(2,len(cost)+1):
# select the min of cost reaching i from i-1 and the cost reaching
#i from i-2
dp[i]=min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2])
#return the cost of reaching top
return dp[-1]