赞
踩
按照这种方法自己做出来了,有点进步
- class Solution:
- def uniquePaths(self, m: int, n: int) -> int:
- dp = [[0] * n for _ in range(m)]
- for j in range(n):
- dp[0][j] = 1
- for i in range(m):
- dp[i][0] = 1
- for i in range(1, m):
- for j in range(1, n):
- dp[i][j] = dp[i][j - 1] + dp[i - 1][j]
- return dp[-1][-1]
遇到障碍的时候dp赋值为0,要注意在初始化的时候,只要遇到障碍,后面的数值都置为0,因为不可能到达了
- class Solution:
- def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
- m = len(obstacleGrid)
- n = len(obstacleGrid[0])
- dp = [[0] * n for _ in range(m)]
- for i in range(m):
- if obstacleGrid[i][0] != 0:
- break
- else:
- dp[i][0] = 1
- for j in range(n):
- if obstacleGrid[0][j] != 0:
- break
- 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][j-1] + dp[i-1][j]
- return dp[-1][-1]
注意:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。