题目
https://leetcode-cn.com/problems/minimum-path-sum/
给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。
说明:每次只能向下或者向右移动一步。
难度:中等
思路
1.动态规划,开辟一个mxn的数组,存储当前的最小值,最小值实际就是左和上两者中小较小的加上当前的值。
2.由于每个用过的元素不会二次使用,因此可以直接更新当前的数组,不用新开辟,可以节省内存
解法
1.动态规划。
//leetcode submit region begin(Prohibit modification and deletion)
class minPathSumx {
public int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int rows = grid.length, columns = grid[0].length;
int[][] dp = new int[rows][columns];
dp[0][0] = grid[0][0];
for (int i = 1; i < rows; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
for (int j = 1; j < columns; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
for (int i = 1; i < rows; i++) {
for (int j = 1; j < columns; j++) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
return dp[rows - 1][columns - 1];
}
//leetcode submit region end(Prohibit modification and deletion)
2.动态规划,不开辟dp。
//leetcode submit region begin(Prohibit modification and deletion)
class minPathSumx {
public int minPathSum(int[][] grid) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (0 == i && 0 == j) continue;
else if (0 == i) grid[i][j] += grid[i][j - 1];
else if (0 == j) grid[i][j] += grid[i - 1][j];
else grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]);
}
}
return grid[rows - 1][columns - 1];
}
//leetcode submit region end(Prohibit modification and deletion)