【代码随想录练习营】【Day 41】【动态规划-1 and 2】| Leetcode 509, 70, 746, 62, 63
需强化知识点
标题
509. 斐波那契数
- class Solution:
- def fib(self, n: int) -> int:
- if n == 0:
- return 0
- if n == 1:
- return 1
- dp = [0] * (n+1)
- dp[0], dp[1] = 0, 1
- for i in range(2, n+1):
- dp[i] = dp[i-1] + dp[i-2]
-
- return dp[n]
复制代码 70. 爬楼梯
- class Solution:
- def climbStairs(self, n: int) -> int:
- if n == 1:
- return 1
- if n == 2:
- return 2
- dp = [1] * n
- dp[0], dp[1] = 1, 2
- for i in range(2, n):
- dp[i] = dp[i-1] + dp[i-2]
-
- return dp[n-1]
复制代码 746. 使用最小花费爬楼梯
- class Solution:
- def minCostClimbingStairs(self, cost: List[int]) -> int:
- # 爬上台阶 i 所需支付的费用
- 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[len(cost)]
复制代码 62. 不同路径
- class Solution:
- def uniquePaths(self, m: int, n: int) -> int:
- dp = [[0] * n for _ in range(m)]
- for i in range(m):
- dp[i][0] = 1
- for i in range(n):
- dp[0][i] = 1
-
- for i in range(1, m):
- for j in range(1, n):
- dp[i][j] = dp[i-1][j] + dp[i][j-1]
-
- return dp[m-1][n-1]
复制代码 63. 不同路径 II
- class Solution:
- def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
- m, n = len(obstacleGrid), len(obstacleGrid[0])
- dp = [[0] * n for _ in range(m)]
- for i in range(m):
- if obstacleGrid[i][0] == 1:
- break
- dp[i][0] = 1
-
- for i in range(n):
- if obstacleGrid[0][i] == 1:
- break
- dp[0][i] = 1
-
- for i in range(1, m):
- for j in range(1, n):
- if obstacleGrid[i][j] == 1:
- continue
- dp[i][j] = dp[i-1][j] + dp[i][j-1]
-
- return dp[m-1][n-1]
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |