首页 > 其他 > 详细

[Lintcode]Minimum Path Sum

时间:2015-12-02 06:37:41      阅读:233      评论:0      收藏:0      [点我收藏+]

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.

Example
 
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) {
        // write your code here
        if(grid.length==0 || grid[0].length==0) return 0;
        int m=grid.length;
        int n=grid[0].length;
     
        int[][] sum=new int[m][n];
        int minSum;
        

        for(int i=0;i<m;i++)
        {
           for(int j=0;j<n;j++)
            {
                if(i==0&&j==0)
                {
                    minSum=0;
                }
                else if(i==0) {minSum=sum[0][j-1];}
                else if(j==0) {minSum=sum[i-1][0];}
                else
                {
                  minSum=Math.min(sum[i-1][j],sum[i][j-1]);
                }
                
                sum[i][j]=minSum+grid[i][j];
            }
        }
        
        return sum[m-1][n-1];
    }
}

 

[Lintcode]Minimum Path Sum

原文:http://www.cnblogs.com/kittyamin/p/5011839.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!