码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Minimum Path Sum

时间:2016-03-03 07:56:52      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

动态规划,比较直接,不多说了

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 == null || grid.length == 0 || grid[0] == null || grid[0].length == 0)
            return 0;
        
        int m = grid.length;
        int n = grid[0].length;
        int[][] result = new int[m][n];
        result[0][0] = grid[0][0];
        
        for(int i = 1; i < n; i++)
            result[0][i] = result[0][i - 1] + grid[0][i];
        for(int i = 1; i < m; i++)
            result[i][0] = result[i - 1][0] + grid[i][0];
        
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                result[i][j] = grid[i][j] + Math.min(result[i - 1][j], result[i][j - 1]);
            }
        }
        
        return result[m - 1][n - 1];
    }
}

 

lintcode-easy-Minimum Path Sum

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5237171.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!