tasks for today:
1. 62.不同路径
2. 63.不同路径II
3. 343.整数拆分(optional)
4. 96.不同的二叉搜索树(optional)
---------------------------------------------------------------------------------
1. 62.不同路径
following the 5-step format for dynamic programming problem, this practice is quit easy.
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1] * n for i 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]
2. 63.不同路径II
The key to solve this practice is that, if obstacle[0][j] and obstacle[i][0] are presented, it equals ro the circumstance that all the block behind it also have obstacles.
Then all the obstacles within the map will cause a zero in dp.
It is worth noting that, when the obstcles are at the start point or the final point, this will lead to a zero answer whatsoever.
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid[0])
n = len(obstacleGrid)
if obstacleGrid[-1][-1] == 1 or obstacleGrid[0][0] == 1:
return 0
dp = [[1] * m for _ in range(n)]
for i in range(m):
if obstacleGrid[0][i] == 1:
for j in range(i + 1, m):
obstacleGrid[0][j] = 1
break
for i in range(n):
if obstacleGrid[i][0] == 1:
for j in range(i + 1, n):
obstacleGrid[j][0] = 1
break
for i in range(1, n):
for j in range(1, m):
if obstacleGrid[i-1][j] == 1:
left = 0
else:
left = dp[i-1][j]
if obstacleGrid[i][j-1] == 1:
right = 0
else:
right = dp[i][j-1]
dp[i][j] = left + right
return dp[-1][-1]