首页 > 代码库 > 【leetcode】Minimum Path Sum
【leetcode】Minimum Path Sum
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 Paths这道题,只是初始化和更新answer数组的方式不同。
代码如下(Java):
1 public class Solution { 2 public int minPathSum(int[][] grid) { 3 int m = grid.length; 4 int n = grid[0].length; 5 int[][] answer = new int[m][n]; 6 7 answer[0][0] = grid[0][0]; 8 for(int i = 1;i < m;i++) 9 answer[i][0] = answer[i-1][0] + grid[i][0];10 for(int i = 1;i < n;i++)11 answer[0][i] = answer[0][i-1] + grid[0][i];12 13 14 for(int i = 1;i < m;i++)15 {16 for(int j = 1;j < n;j++){17 answer[i][j] = Math.min(answer[i-1][j],answer[i][j-1])+grid[i][j] ;18 }19 }20 21 return answer[m-1][n-1];22 }23 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。