代码随想录算法训练营第36天 | 动态规划基础2:62.不同路径、63.不同路径 II
62.不同路径
https://leetcode.cn/problems/unique-paths/submissions/548656029/
代码随想录
https://programmercarl.com/0062.不同路径.html
63.不同路径 II
https://leetcode.cn/problems/unique-paths-ii/description/
代码随想录
https://programmercarl.com/0063.不同路径II.html#算法公开课
343.整数拆分(一刷跳过)
https://leetcode.cn/problems/integer-break/
代码随想录
https://programmercarl.com/0343.整数拆分.html
96.不同的二叉搜索树(一刷跳过)
https://leetcode.cn/problems/unique-binary-search-trees/description/
代码随想录
https://programmercarl.com/0096.不同的二叉搜索树.html
62.不同路径
题解思路
- 思路一:动态规划算法:
- dp[i][j]代表到第i行第j列的格子的可能性;
- dp[i][j] = dp[i-1][j]+dp[i][j-1]
- 排列组合计算
-计算 $ C(m+n-2,m-1) $
题解代码
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1]*n for _ in range(m)]
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[-1][-1]
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
count = m-1
t = m+n-2
fenmu = m-1
fenzi = 1
while count>0:
fenzi*=t ##分子已知变化
t-=1
while fenmu!=0 and fenzi%fenmu==0:###除得尽再除
fenzi //= fenmu
fenmu -=1
count-=1
return fenzi
63.不同路径 II
题解思路
- 和一比只需要多处理几个关于障碍的特殊情况
- 障碍在起点和终点 直接为0
- 初始化时,如果出现障碍,剩下的全为0
题解代码
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
## 绝路不计算
if obstacleGrid[0][0]==1 or obstacleGrid[-1][-1]:
return 0
dp = [[0]*n for _ in range(m)]
for i in range(n):
if obstacleGrid[0][i]!=1:
dp[0][i] = 1
else:
break
for j in range(m):
if obstacleGrid[j][0]!=1:
dp[j][0] = 1
else:
break
for i in range(1,m):
for j in range(1,n):
if obstacleGrid[i][j]==1:
dp[i][j] = 0
else:
dp[i][j] = dp[i-1][j]+dp[i][j-1]
return dp[-1][-1]