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.

s[i][j] = a[i][j] + min(s[i-1][j],if i > 0;s[i][j-1],if j > 0) ，但是这里要注意的是针对s[0][0]的那一个格子，因为是从一行和一列开始的，所以当遇到s[0][0]的时候，我是直接将其赋为nums[0][0]的那个值，另外当遇到的是第一行和第一列的时候，因为没有s[i-1][j]和s[i][j-1]，所以我在设置这些格子的时候采用Integer.MAX_VALUE，这个最大值来做，这样就可以比较最小的那个了。

public class NumArray
{
public static int minPathSum(int[][] nums)
{
int n = nums.length;
int m = nums[0].length;
//System.out.println(m);
int[][] S = new int[n][m];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
int increment = nums[i][j];
//System.out.print(increment + "  ");
int left = 0,up = 0;
if(i == 0 && j == 0)
S[i][j] =increment;
else
{
if(i > 0)
up = S[i-1][j];
else
up = Integer.MAX_VALUE;
if(j > 0)
left = S[i][j - 1];
else
left = Integer.MAX_VALUE;
int neighbor = 0;
if(up <= left)
neighbor = up;
else
neighbor = left;
S[i][j] = neighbor + increment;
}
}
}
int result = S[n-1][m-1];
return result;
}
public static void main(String[] args)
{
int[][] nums = new int[][]{{1,2},{1,1}};
System.out.println(minPathSum(nums));
}
}

10-19 4616

05-31 2384

07-17 1286

02-17 370

02-26 2623

02-04 1883

08-02 2627

10-07 296

05-06 1072

05-25 1988