minimum-path-sum

原创 2015年07月07日 10:00:28

容易 最小路径和

34%
通过

给定一个只含非负整数的m*n网格,找到一条从左上角到右下角的可以使数字和最小的路径。


您在真实的面试中是否遇到过这个题? 
Yes
样例
注意

你在同一时间只能向下或者向右移动一步


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

相关文章推荐

动态规划--最小路径和(Minimum Path Sum)

原题   Given a m x n grid filled with non-negative numbers, find a path from top left to bottom rig...

Leetcode64 Minimum Path Sum

Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to...

leetcode[63] Minimum Path Sum 动态规划

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...

LeetCode刷题(C++)——Minimum Path Sum(Medium)

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...

LeetCode 1.Minimum Path Sum 2.Unique Paths I and II

大家好,我是刘天昊,快到端午节了,今天说两道动态规划的题目(话说动规真的挺难的) 当然这三题是一样的解体思路先看Unique Paths  A robot is located a...

LeetCode: Minimum Path Sum [063]

【题目】 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom righ...

leetcode笔记:Minimum Path Sum

题目的大意是,给定一个m*n的网格,每个格子里有一个非负整数,找到一条从左上角到右下角的路径,使其经过的格子数值之和最小,每一步只能向右或向下走。可使用动态规划来解决该问题。...

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

LeetCode Solutions : Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...
  • lviiii
  • lviiii
  • 2014年08月11日 13:55
  • 489

Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:minimum-path-sum
举报原因:
原因补充:

(最多只允许输入30个字)