动态规划 Part2
62.不同路径
题目链接:力扣题目链接
思路:
- dp[i][j]表示到达第[i][j]点的方式
- 第一排和第一列都是 1 种
- dp[i][j] = dp[i][j - 1] + dp[i - 1][j]
实现代码:
var uniquePaths = function(m, n) {
let dp = new Array(m).fill(0).map(item => new Array(n).fill(0))
for(let k = 0; k < m; k = k + 1) {
dp[k][0] = 1
}
for(let l = 0; l < n ; l = l + 1) {
dp[0][l] = 1
}
for(let i = 1;i < m; i= i + 1) {
for(let j = 1; j <n; j = j + 1) {
dp[i][j] = dp[i][j - 1] + dp[i - 1][j]
}
}
return dp[m - 1][n - 1]
};
63. 不同路径 II
题目链接: 力扣题目链接
思路:这里遇到障碍物也就是 obstacles[i][j]=== 1的情况,就得跳过
实现代码:
var uniquePathsWithObstacles = function (obstacleGrid) {
let m = obstacleGrid.length
let n = obstacleGrid[0].length
let dp = new Array(m).fill(0).map(() => new Array(n).fill(0))
for (let k = 0; k < m; k = k + 1) {
console.log(obstacleGrid[k][0])
if (obstacleGrid[k][0] === 1) break
dp[k][0] = 1
}
for (let l = 0; l < n; l = l + 1) {
if (obstacleGrid[0][l] === 1) break
dp[0][l] = 1
}
console.log(dp)
for(let i = 1; i < m; i = i + 1) {
for(let j = 1; j < n; j = j +1) {
if(obstacleGrid[i][j] !== 1) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
}
}
}
return dp[m-1][n-1]
};