目录
学习目标
- 理论基础
- 509. 斐波那契数
- 70. 爬楼梯
- 746. 使用最小花费爬楼梯
学习内容
理论基础
509. 斐波那契数
509. 斐波那契数 - 力扣(LeetCode)https://leetcode.cn/problems/fibonacci-number/
class Solution:
def fib(self, n: int) -> int:
def dfs(i):
if i<2:return i
return dfs(i-1)+dfs(i-2)
return dfs(n)
class Solution:
def fib(self, n: int) -> int:
@cache
def dfs(i):
if i<2:return i
return dfs(i-1)+dfs(i-2)
return dfs(n)
class Solution:
def fib(self, n: int) -> int:
if n<2:return n
f = [0]*(n+1)
f[1]=1
for i in range(2,n+1):
f[i] = f[i-1]+f[i-2]
return f[n]
class Solution:
def fib(self, n: int) -> int:
if n<2:return n
a = 0
b = 1
for i in range(2,n+1):
a,b=b,a+b
return b
70. 爬楼梯
70. 爬楼梯 - 力扣(LeetCode)https://leetcode.cn/problems/climbing-stairs/
class Solution:
def climbStairs(self, n: int) -> int:
@cache
def dfs(i):
if i<2:return 1
return dfs(i-1)+dfs(i-2)
return dfs(n)
class Solution:
def climbStairs(self, n: int) -> int:
if n<2:return 1
f = [1]*(n+1)
for i in range(2,n+1):
f[i]=f[i-1]+f[i-2]
return f[n]
746. 使用最小花费爬楼梯
746. 使用最小花费爬楼梯 - 力扣(LeetCode)https://leetcode.cn/problems/min-cost-climbing-stairs/
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
@cache
def dfs(i):
if i<2:return 0
return min(dfs(i-1)+cost[i-1],dfs(i-2)+cost[i-2])
return dfs(len(cost))
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
n = len(cost)
f = [0]*(n+1)
for i in range(2,n+1):
f[i] = min(f[i-1]+cost[i-1],f[i-2]+cost[i-2])
return f[n]