中文版:
给定一个只含非负整数的m*n网格,找到一条从左上角到右下角的可以使数字和最小的路径。
注意
你在同一时间只能向下或者向右移动一步.
English Version
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.
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) {
if(null==grid||0==grid.length||0==grid[0].length)return 0;
int m=grid.length;
int n=grid[0].length;
int[] dp=new int[n];
dp[0]=grid[0][0];
for(int i=1;i<n;i++){
dp[i]+=dp[i-1] + grid[0][i];
}
for(int i=1;i<m;i++){
dp[0]+=grid[i][0];
for(int j=1;j<n;j++){
dp[j]=Math.min(dp[j],dp[j-1])+grid[i][j];
}
}
return dp[n-1];
}
}