func uniquePaths(m int, n int) int {
// dp数组的含义:从(0,0)到(i,j)一共有多少种不同的走法
dp := make([][]int, m) //例如m=2,n=3 [][]
// 初始化dp数组:最上面和最左边初始值为1,因为只有一种走法
for i := 0; i < m; i++ {
dp[i] = make([]int, n)
dp[i][0] = 1
}
for j := 0; j < n; j++ {
dp[0][j] = 1
}
//遍历顺序为从左到右从上到下,注意i,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 {
//如果起始位置或者终止位置有障碍则返回0
m, n := len(obstacleGrid), len(obstacleGrid[0])
if obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1 {
return 0
}
// dp数组的含义:从(0,0)到(i,j)共有多少种走法
dp := make([][]int, m)
//注意这里要提前初始化二维数组
for i := 0; i < m; i++ {
dp[i] = make([]int, n)
dp[i][0] = 0
}
//初始化dp数组,如果障碍出现在上边界或者左边界则之后的元素为0
for i := 0; i < m && obstacleGrid[i][0] == 0; i++ {
dp[i] = make([]int, n)
dp[i][0] = 1
}
for j := 0; j < n && obstacleGrid[0][j] == 0; j++ {
dp[0][j] = 1
}
//遍历顺序为从左到右从上到下,注意i,j均从1开始
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
//递推公式
if obstacleGrid[i][j] == 0 {
dp[i][j] = dp[i-1][j] + dp[i][j-1]
}
}
}
return dp[m-1][n-1]
}