理論基礎
- 斐波那契數
class Solution:
def fib(self, n: int) -> int:
if n == 0:
return 0
if n == 1:
return 1
return self.fib(n-1)+self.fib(n-2)
- 爬樓梯
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 1:
return n
dp = [0] * 3
dp[1] = 1
dp[2] = 2
total = 0
for i in range(3, n+1):
total = dp[1] + dp[2]
dp[1] = dp[2]
dp[2] = total
return dp[2]
- 使用最小花費爬樓梯
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
dp = [0] *(len(cost) + 1)
dp[0] = 0
dp[1] = 0
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]