We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
原题链接
dp[i][j] 代表从 (0, 0) 走到 (i, j) 的最小路径和。
dp[i][j]
明确题意:只能向右或者向下走,也就是说终点 (i, j) 只能从 (i - 1, j) 或者 (i, j - 1) 走过来。
分为以下三种情况分别处理:
dp[i][j] = grid[i][j]
grid[i][j] = grid[i - 1][j] + grid[i][j]
grid[i][j] = grid[i][j - 1] + grid[i][j]
grid[i][j] = Math.min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j]
const minPathSum = function(grid) { const n = grid.length const m = grid[0].length const dp = Array.from(new Array(n), () => new Array(m)) for (let i = 0; i < n ; i++) { for (let j = 0; j < m; j++) { if (i !== 0 && j !== 0) { dp[i][j] = Math.min(dp[i - 1][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 if (i === 0 && j !== 0) { dp[i][j] = dp[i][j - 1] + grid[i][j] } else if (i === 0 && j === 0) { dp[i][j] = grid[i][j] } } } return dp[n - 1][m - 1] }
不需要额外建立空间,直接遍历修改 grid[i][j]。
grid[i][j]
const minPathSum = function(grid) { const n = grid.length const m = grid[0].length for (let i = 0; i < n ; i++) { for (let j = 0; j < m; j++) { if (i !== 0 && j !== 0) { grid[i][j] = Math.min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j] } else if (i !== 0 && j === 0) { grid[i][j] = grid[i - 1][j] + grid[i][j] } else if (i === 0 && j !== 0) { grid[i][j] = grid[i][j - 1] + grid[i][j] } else if (i === 0 && j === 0) { grid[i][j] = grid[i][j] } } } return grid[n - 1][m - 1] }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接
状态定义
dp[i][j]
代表从 (0, 0) 走到 (i, j) 的最小路径和。状态转移方程
明确题意:只能向右或者向下走,也就是说终点 (i, j) 只能从 (i - 1, j) 或者 (i, j - 1) 走过来。
分为以下三种情况分别处理:
dp[i][j] = grid[i][j]
grid[i][j] = grid[i - 1][j] + grid[i][j]
grid[i][j] = grid[i][j - 1] + grid[i][j]
grid[i][j] = Math.min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j]
降维
不需要额外建立空间,直接遍历修改
grid[i][j]
。The text was updated successfully, but these errors were encountered: