首页 > 代码库 > Minimum Path Sum
Minimum Path Sum
public class Solution { /** * @param grid: a list of lists of integers. * @return: An integer, minimizes the sum of all numbers along its path */ public int minPathSum(int[][] grid) { // write your code here if (grid == null || grid.length == 0) { return 0; } if (grid[0] == null || grid[0].length == 0) { return 0; } int nRow = grid.length; int nCol = grid[0].length; int[][] f = new int[nRow][nCol]; //f[x][y]: minimum path sum from (0, 0) to (x, y) f[0][0] = grid[0][0]; for (int i = 1; i < nCol; i++) { f[0][i] = f[0][i - 1] + grid[0][i]; } for (int i = 1; i < nRow; i++) { f[i][0] = f[i - 1][0] + grid[i][0]; } for (int i = 1; i < nRow; i++) { for (int j = 1; j < nCol; j++) { f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + grid[i][j]; } } return f[nRow - 1][nCol - 1]; } }
Minimum Path Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。