func uniquePaths(m int, n int) int {
dp := make([][]int, m)
// 行赋初始值为1
for i := range dp {
dp[i] = make([]int, n)
dp[i][0] = 1
}
// 列赋初始值为1
for j := 0; j < n; j++ {
dp[0][j] = 1
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
dp[i][j] = dp[i-1][j] + dp[i][j-1]
}
}
return dp[m-1][n-1]
}
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
m := len(obstacleGrid)
n := len(obstacleGrid[0])
//如果在起点或终点出现了障碍,直接返回0
if obstacleGrid[m-1][n-1] == 1 || obstacleGrid[0][0] == 1 {
return 0
}
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, n)
}
// 行赋初始值为1,有障碍物停止
for i := 0; i < m && obstacleGrid[i][0] == 0; i++ {
dp[i][0] = 1
}
// 列赋初始值为1,有障碍物停止
for j := 0; j < n && obstacleGrid[0][j] == 0; j++ {
dp[0][j] = 1
}
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]
}
}
}
return dp[m-1][n-1]
}