您的位置:首页 > 其它

LeetCode刷题笔录Minimum Path Sum

2014-07-04 05:56 357 查看
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.

标准的Dynamic Programming。注意第一行的元素只能从左边走过来,第一列的只能从上边走下来。

public class Solution {
public int minPathSum(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
int[][] result = new int[m]
;
//fill the first row of result, i.e. result[0]
int sum = 0;
for(int i = 0; i < n; i++){
sum += grid[0][i];
result[0][i] = sum;
}
//fill the first column
sum = 0;
for(int j = 0; j < m; j++){
sum += grid[j][0];
result[j][0] = sum;
}

//fill the rest
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
result[i][j] = Math.min(result[i - 1][j], result[i][j - 1]) + grid[i][j];
}
}
return result[m - 1][n - 1];

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