您的位置:首页 > 其它

LeetCode Minimum Path Sum

2014-09-29 20:14 344 查看


Minimum Path Sum

Total Accepted: 18319 Total
Submissions: 58624My Submissions

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.

Have you been asked this question in an interview?

public class Solution {
public int minPathSum(int[][] grid) {
if (grid == null){
return 0;
}
int[][] result = new int[grid.length][grid[0].length];
result[0][0] = grid[0][0];
for (int i = 1; i < grid.length; i++) {
result[i][0] = grid[i][0] + result[i - 1][0];
}
for (int i = 1; i < grid[0].length; i++) {
result[0][i] = grid[0][i] + result[0][i - 1];
}
for (int i = 1; i < grid.length; i++) {
for (int j = 1; j < grid[0].length; j++) {
result[i][j] = Math.min(grid[i][j] + result[i][j - 1], grid[i][j] + result[i - 1][j]);
}
}
return result[grid.length - 1][grid[0].length - 1];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: