title: LEETCODE-DAY39
date: 2024-03-30 17:24:46
tags:
今日内容:62.不同路径、63. 不同路径 II
T1
python
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp=[[0 for _ in range(n+1)]for _ in range(m+1)]
dp[1][1]=1
for i in range(1,m+1):
for j in range(1,n+1):
dp[i][j]=dp[i-1][j]+dp[i][j-1]
return dp[m][n]
输入
m =
3
n =
2
输出
0
预期结果
3
dp[1][1]被覆盖了
python
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp=[[0 for _ in range(n+1)]for _ in range(m+1)]
dp[1][1]=1
for i in range(1,m+1):
for j in range(1,n+1):
if i==1 and j==1:
continue
dp[i][j]=dp[i-1][j]+dp[i][j-1]
return dp[m][n]
AC
T2
python
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m=len(obstacleGrid)
n=len(obstacleGrid[0])
dp=[[0 for _ in range(n)]for _ in range(m)]
for i in range(m):
dp[i][0]=1
for j in range(n):
dp[0][j]=1
for i in range(1,m):
for j in range(1,n):
dp[i][j]=dp[i-1][j]+dp[i][j-1]
res=dp[m-1][n-1]
for i in range(m):
for j in range(n):
if obstacleGrid[i][j]==1:
res-=dp[i][j]*dp[m-i-1][n-j-1]
return res
输入
obstacleGrid =
[[1,1]]
输出
-1
预期结果
0
python
#同上
return max(res,0)
输入
obstacleGrid =
[[0,0,0,0],[0,1,0,0],[0,0,0,0],[0,0,1,0],[0,0,0,0]]
输出
0
预期结果
7
需要换一种思路
python
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m=len(obstacleGrid)
n=len(obstacleGrid[0])
dp=[[0 for _ in range(n)]for _ in range(m)]
if obstacleGrid[0][0]==1:
return 0
for i in range(m):
if obstacleGrid[i][0]==1:
dp[i][0]=0
else:
dp[i][0]=1
for j in range(n):
if obstacleGrid[0][j]==1:
dp[0][j]=0
else:
dp[0][j]=1
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[m-1][n-1]
输入
obstacleGrid =
[[0,0],[1,1],[0,0]]
输出
1
预期结果
0
初始化有问题
第一行遇到障碍后障碍之后的列也应初始化为0
python
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m=len(obstacleGrid)
n=len(obstacleGrid[0])
dp=[[0 for _ in range(n)]for _ in range(m)]
if obstacleGrid[0][0]==1:
return 0
for i in range(m):
if obstacleGrid[i][0]==1:
dp[i][0]=0
elif i>0 and dp[i-1][0]==0:
dp[i][0]=0
else:
dp[i][0]=1
for j in range(n):
if obstacleGrid[0][j]==1:
dp[0][j]=0
elif j>0 and dp[0][j-1]==0:
dp[0][j]=0
else:
dp[0][j]=1
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[m-1][n-1]
AC
python
python