-
Notifications
You must be signed in to change notification settings - Fork 633
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
leetcode64:最小路径和 #139
Comments
1、DP方程 2、边界处理 for(let j = 1; j < col; j++) grid[0][j] += grid[0][j - 1] 计算第一列: for(let i = 1; i < row; i++) grid[i][0] += grid[i - 1][0] 3、代码实现 var minPathSum = function(grid) {
let row = grid.length, col = grid[0].length
// calc boundary
for(let i = 1; i < row; i++)
// calc first col
grid[i][0] += grid[i - 1][0]
for(let j = 1; j < col; j++)
// calc first row
grid[0][j] += grid[0][j - 1]
for(let i = 1; i < row; i++)
for(let j = 1; j < col; j++)
grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1])
return grid[row - 1][col - 1]
}; |
这里计算的方向是从右下角到左上角吧 |
/**
*
* @param {number[][]} grid
*/
function minPathSum(grid) {
if (grid.length < 1 || grid[0].length < 1) {
return 0
}
let m = grid.length
let n = grid[0].length
let dp = new Array(m).fill(undefined).map(() => {
return new Array(n).fill(0)
})
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
// 左上角
if (i === 0 && j === 0) {
dp[0][0] = grid[0][0]
} else if (i == 0 && j !== 0) {
// 第一行
dp[i][j] = dp[i][j - 1] + grid[i][j]
} else if (i != 0 && j == 0) {
// 第一列
dp[i][j] = dp[i - 1][j] + grid[i][j]
} else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
}
}
}
return dp[m - 1][n - 1]
} |
看了labuladong 写的 click here var minPathSum = function(grid) {
let m = grid.length
let n = grid[0].length
// 备忘录
let memo = Array.from({length: m}, ()=> Array(n).fill(9999))
// dp的定义 - 当前坐标最小的路径和
const dp = (matrix, i, j, memo) => {
// 处理合法性
if (i<0 || j<0) {
return 10000
}
// base case
if(i ===0 && j === 0) {
return matrix[0][0]
}
// 备忘录
if (memo[i][j] !== 9999) {
return memo[i][j]
}
// 当前dp值 = 该点的坐标值 + 左方 和 上方的dp 值
memo[i][j] = matrix[i][j]+ Math.min(dp(matrix, i-1, j, memo), dp(matrix, i, j-1, memo))
return memo[i][j]
}
// 将终点坐标带入
return dp(grid, m-1, n-1, memo)
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给定一个包含非负整数的
m x n
网格grid
,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。说明:每次只能向下或者向右移动一步。
示例 1:
示例 2:
提示:
m == grid.length
n == grid[i].length
1 <= m, n <= 200
0 <= grid[i][j] <= 100
leetcode
The text was updated successfully, but these errors were encountered: