leetcode 64. 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.

 

和62,63题类似,转移方程变成了从上面来和从左边来的更小的值加上自己的数字。要注意(0,0)点特殊情况

 

public class Solution {
    public int minPathSum(int[][] grid) {
        int m=grid.length;
        int n=grid[0].length;
        int[][] path=new int[m][n];
      for(int i=0;i<m;i++){
            for(int j=0; j<n;j++){
                int min=Integer.MAX_VALUE;
                if(i-1>=0){
                    min =Integer.min(min,path[i-1][j]) ;
                }
                if(j-1>=0){
                    min= Integer.min(min,path[i][j-1]);
                }
                if (i==0&&j==0){
                    min=0;
                }
                path[i][j]=min+grid[i][j];
            }
        }
        return path[m-1][n-1];
    }
}

 

posted on 2017-07-03 14:31  sure0328  阅读(70)  评论(0)    收藏  举报

导航