资讯专栏INFORMATION COLUMN

[LintCode/LeetCode] Minimum Path Sum

CntChen / 2141人阅读

摘要:遍历整个矩阵,对于,取上方和左边较小值,与相加可得该点最小值。

Problem

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.

You can only move either down or right at any point in time.

Note

遍历整个矩阵,对于dp[i][j],取上方dp[i-1][j]和左边dp[i][j-1]较小值,与grid[i][j]相加可得该点最小值。

Solution
public class Solution {
    public int minPathSum(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int[][] dp = new int[m][n];
        dp[0][0] = grid[0][0];
        for (int i = 1; i < m; i++) {
            dp[i][0] = dp[i-1][0] + grid[i][0];
        }
        for (int i = 1; i < n; i++) {
            dp[0][i] = dp[0][i-1] + grid[0][i];
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
            }
        }
        return dp[m-1][n-1];
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65788.html

相关文章

  • [LintCode/LeetCode] Triangle

    摘要:第一种方法是很早之前写的,先对三角形两条斜边赋值,和分别等于两条斜边上一个点的和与当前点的和。然后套用动规公式进行横纵坐标的循环计算所有点的,再遍历最后一行的,找到最小值即可。 Problem Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacen...

    刘德刚 评论0 收藏0
  • [LintCode/LeetCode] Binary Tree Maximum Path Sum

    摘要:调用函数更新路径和的最大值,而函数本身需要递归,返回的是单边路径和。所以函数要返回的是,主函数中返回的却是最上一层根节点处和的较大值,与之前遍历过所有路径的最大值之间的最大值。 Problem Given a binary tree, find the maximum path sum. The path may start and end at any node in the tre...

    cnTomato 评论0 收藏0
  • [LintCode/LeetCode] Minimum Window Substring

    Problem Given a string source and a string target, find the minimum window in source which will contain all the characters in target. Notice If there is no such window in source that covers all charac...

    Corwien 评论0 收藏0
  • [LintCode/LeetCode] Find Minimum in Rotated Sorted

    摘要:排序数组中找最小值或最大值的题目,很明显可以使用二分法。因此,只判断终点和中点元素的大小关系即可。这里有一种情况是上述后三个,中点值和末位相等。此时,两边同时递归,并返回两边递归值的较小值。当首位和末位重合,说明已夹逼得到最小值。 Find Minimum in Rotated Sorted Array Problem Suppose a sorted array is rotated...

    cgh1999520 评论0 收藏0
  • [LintCode/LeetCode] Integer Replacement

    Problem Given a positive integer n and you can do operations as follow: 1.If n is even, replace n with n/2.2.If n is odd, you can replace n with either n + 1 or n - 1. What is the minimum number of re...

    fyber 评论0 收藏0

发表评论

0条评论

CntChen

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<