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]