思路: 在不同路径的基础上 1.初始化时若碰到障碍物,dp后面全部是0 2.在遍历求解时遇到障碍,dp[i][j] = 0
代码:
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
m := len(obstacleGrid)
n := len(obstacleGrid[0])
dp := make([][]int, m)
for i := 0; i < m; i++ {
dp[i] = make([]int, n)
}
for i := 0; i < n; i++ {
if obstacleGrid[0][i] != 1{
dp[0][i] = 1
} else {
break
}
}
for i := 0; i < m; i++ {
if obstacleGrid[i][0] != 1{
dp[i][0] = 1
} else {
break
}
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
if obstacleGrid[i][j] != 1 {
dp[i][j] = dp[i-1][j] + dp[i][j-1]
} else {
dp[i][j] = 0
}
}
}
return dp[m-1][n-1]
}
|