您的位置:首页 > 其它

个人记录-LeetCode 64. Minimum Path Sum

2016-12-30 19:40 453 查看
问题:

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

问题的思路与Unique PathsUnique Paths II一致。

唯一不同的是,每个位置保留的结果不再是到达该位置的走法,而是到达该位置最小的sum。

代码示例:

public class Solution {
public int minPathSum(int[][] grid) {
if (grid == null || grid.length < 1 || grid[0].length < 1) {
return 0;
}

int m = grid.length;
int n = grid[0].length;

//初始化
//由于参数数组中也可以含有0,因此边缘初始化为-1
int[][] rst = new int[m+1][n+1];
for (int i = 0; i <= m; ++i) {
rst[i][0] = -1;
}
for (int j = 0; j <= n; ++j) {
rst[0][j]  = -1;
}

for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
//第一个位置
if (i == 1 && j == 1) {
rst[1][1] = grid[0][0];
continue;
}

//特殊处理第1行和第1列
if (rst[i][j-1] == -1) {
rst[i][j] = rst[i-1][j] + grid[i-1][j-1];
} else if (rst[i-1][j] == -1){
rst[i][j] = rst[i][j-1] + grid[i-1][j-1];
} else {
//其它位置,等于当前位置的值,与min(前一列,上一行)的和
rst[i][j] = grid[i-1][j-1]
+ (rst[i-1][j] > rst[i][j-1] ? rst[i][j-1] : rst[i-1][j]);
}
}
}

return rst[m]
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: