今天的题不难,还是按照五步走就行
62. Unique Paths
五步走战略即可: dp[i][j]代表的是到当前的位置位置一共有多少条path. 遍历是从左到右从上到下.每个dp和左和上有关,初始第一行和第一列即可
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp=[[0 for _ in range(n)] for _ in range(m)]
for i in range(n):
dp[0][i]=1
for j in range(m):
dp[j][0]=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[-1][-1]
63. Unique Paths II
这道题就是在上一道题的基础上加个判断条件即可,如果当前dp对应的地方是个石头就不用管,如果不是是石头就更新dp
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(n):
if obstacleGrid[0][i]==1:
break
dp[0][i]=1
for j in range(m):
if obstacleGrid[j][0]==1:
break
dp[j][0]=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[-1][-1]