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

[LeetCode] 64. Minimum Path Sum 最小路径和

时间:2018-02-25 17:19:12      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:gpo   ++   ber   最小   you   blog   dynamic   new   section   

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.

Example 1:

[[1,3,1],
 [1,5,1],
 [4,2,1]]

Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.

解题思路:

依然用动态归化(Dynamic Programming),我们使用dp[i][j]表明从(0, 0)到(i, j)最小的路径和,那么dp方程为:

dp[i][j] = min(dp[i][j-1], dp[i - 1][j]) + grid[i][j]

 

Java:

public class Solution {
    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[][] 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];
    }
}

  

[LeetCode] 64. Minimum Path Sum 最小路径和

标签:gpo   ++   ber   最小   you   blog   dynamic   new   section   

原文地址:https://www.cnblogs.com/lightwindy/p/8469442.html

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