给一个非负数二维数组,从左上到右下,最短的路径
只能向右或者向下走
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
动态规划
这里面存在一个问题,要想求出下一步的最短距离,必须求出上一步的最短距离
边界:mins[0][0] = grid[0][0]
状态转移公式3个:
- grid[0]那一排,依赖于左侧
- grid[x][0]那一列,依赖于上侧
- 其他的依赖于左侧和上侧
class Solution {
public int minPathSum(int[][] grid) {
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}
int[][] mins = new int[grid.length][grid[0].length];
for (int i = 0; i < grid.length; i++) {
int[] gridInner = grid[i];
for (int j = 0; j < gridInner.length; j++) {
if (i == 0) {
if (j == 0) {
mins[i][j] = grid[i][j];
} else {
mins[i][j] = mins[i][j - 1] + grid[i][j];
}
} else {
if (j == 0) {
mins[i][j] = mins[i - 1][j] + grid[i][j];
} else {
mins[i][j] = Math.min(mins[i - 1][j], mins[i][j - 1]) + grid[i][j];
}
}
}
}
return mins[grid.length - 1][grid[0].length - 1];
}
}