leetcode-dp-64
import java.util.Arrays;
import java.util.HashMap;
/**
* <p>给定一个包含非负整数的 <code><em>m</em> x <em>n</em></code> 网格 <code>grid</code> ,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。</p>
*
* <p><strong>说明:</strong>每次只能向下或者向右移动一步。</p>
*
* <p> </p>
*
* <p><strong>示例 1:</strong></p>
* <img alt="" src="https://assets.leetcode.com/uploads/2020/11/05/minpath.jpg" style="width: 242px; height: 242px;" />
* <pre>
* <strong>输入:</strong>grid = [[1,3,1],[1,5,1],[4,2,1]]
* <strong>输出:</strong>7
* <strong>解释:</strong>因为路径 1→3→1→1→1 的总和最小。
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>grid = [[1,2,3],[4,5,6]]
* <strong>输出:</strong>12
* </pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li><code>m == grid.length</code></li>
* <li><code>n == grid[i].length</code></li>
* <li><code>1 <= m, n <= 200</code></li>
* <li><code>0 <= grid[i][j] <= 100</code></li>
* </ul>
* <div><div>Related Topics</div><div><li>数组</li><li>动态规划</li><li>矩阵</li></div></div><br><div><li>👍 1300</li><li>👎 0</li></div>
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
//二维数组作为 备忘录
int[][] memo = new int[m][n];
for (int[] row : memo) {
Arrays.fill(row, -1);
}
return dp(grid, m - 1, n - 1, memo);
}
int dp(int[][] grid, int i, int j, int[][] memo) {
if (i == 0 && j == 0) {
return grid[0][0];
}
if (i < 0 || j < 0) {
return Integer.MAX_VALUE;
}
if (memo[i][j] != -1) {
return memo[i][j];
}
memo[i][j] = Math.min(dp(grid, i - 1, j, memo), dp(grid, i, j - 1, memo)) + grid[i][j];
return memo[i][j];
}
}
//leetcode submit region end(Prohibit modification and deletion)
不恋尘世浮华,不写红尘纷扰