题目链接:509. 斐波那契数 - 力扣(LeetCode)
思路:基础题目
class Solution(object):
def fib(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
elif n == 1:
return 1
else:
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]
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1:
return 1
elif n == 2:
return 2
else:
dp = [0] * (n + 1) #多一个防止排0
dp[1] = 1 #上一阶有一种 1
dp[2] = 2 #上二阶有两种 1 + 1; 2
for i in range(3, n + 1):
dp[i] = dp[i-2] + dp[i-1] #由下两阶跨两步上来,也可以下一阶跨一步上来
return dp[n]
题目链接:746. 使用最小花费爬楼梯 - 力扣(LeetCode)
思路:这题主要是要想清楚楼顶在哪,要多加一位
class Solution(object):
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
if len(cost) == 2:
return min(cost[0], cost[1])
else:
dp = [0] * (len(cost) + 1) #dp数组代表走到当前位置需要花费的最小代价
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[len(cost)]