首页 > 代码库 > Minimum Path Sum
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. Notice You can only move either down or right at any point in time. Have you met this question in a real interview? Yes Example Tags Dynamic Programming Related Problems Easy Triangle 26 % Medium Binary Tree Maximum Path Sum
矩阵的动归, 要初始化边界
public int minPathSum(int[][] grid) { // write your code here if (grid == null || grid.length == 0) { return -1; } int n = grid.length; int m = grid[0].length; //state int[][] sum = new int[n][m]; //initialize sum[0][0] = grid[0][0]; for (int i = 1; i < m; i++) { sum[0][i] = sum[0][i - 1] + grid[0][i]; } for (int i = 1; i < n; i++) { sum[i][0] = sum[i - 1][0] + grid[i][0]; } //top down for (int i = 1; i < n; i++) { for (int j = 1; j < m; j++) { sum[i][j] = Math.min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j]; } } //ans return sum[n - 1][m - 1]; }
Minimum Path Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。