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.
思路 :求grid[0][0]到grid[i][j]的最小和,就必须得出以下公式
public class Solution { public int minPathSum(int[][] grid) { int i,j,min; for(i=1;i<grid.length;i++){ grid[i][0]+=grid[i-1][0]; } for(i=1;i<grid[0].length;i++){ grid[0][i]+=grid[0][i-1]; } for(i=1;i<grid.length;i++){ for(j=1;j<grid[0].length;j++){ min=grid[i-1][j]<grid[i][j-1]?grid[i-1][j]:grid[i][j-1]; grid[i][j]+=min; } } return grid[grid.length-1][grid[0].length-1]; } }
原文地址:http://blog.csdn.net/mlweixiao/article/details/38985871