Leetcode P0064"Minimum Path Sum" 题解

2020/08/28 Leetcode

博文中会简要介绍Leetcode P0064题目分析及解题思路。

“Minimum Path Sum”是p0062的变形题。递推式十分简单,唯一区别在于每个格子多了相当于权重的值。

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.

这道题的思路很直接明了。递推式如下:

    令dp[i][j]表示到第i行第j列位置最小路径和
    
    dp[0][0] = grid[0][0]

    dp[i][0] = dp[i-1][0]+grid[i][0];
    dp[0][j] = dp[0][j-1]+grid[0][j];
    边界只有一条路

    dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1])+grid[i][j];
    任何一个位置的最小和都是来自上面路径的和和来自左边路径的和中的最小值加上自身位置上的权重

以下是Java的题解代码实现。

class Solution {
    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0)
            return 0;
        
        int m = grid.length, n = grid[0].length;
        int[][] dp = new int[m][n];
        dp[0][0] = grid[0][0];
        for (int itr=1; itr<m; ++itr) 
            dp[itr][0] = dp[itr-1][0]+grid[itr][0];
        
        for (int itr=1; itr<n; ++itr) 
            dp[0][itr] = dp[0][itr-1]+grid[0][itr];

        for (int i1=1; i1<m; ++i1) {
            for (int j2=1; j2<n; ++j2) {
                dp[i1][j2] = Math.min(dp[i1-1][j2], dp[i1][j2-1])+grid[i1][j2];
            }
        }
        
        return dp[m-1][n-1];
    }
}

以下是C++的题解代码实现。

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        if (grid.size() == 0)
            return 0;
        
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> dp(m, vector<int>(n, 0));
        dp[0][0] = grid[0][0];
        for (int itr=1; itr<m; ++itr) 
            dp[itr][0] = dp[itr-1][0]+grid[itr][0];
        
        for (int itr=1; itr<n; ++itr) 
            dp[0][itr] = dp[0][itr-1]+grid[0][itr];

        for (int i1=1; i1<m; ++i1) {
            for (int j2=1; j2<n; ++j2) {
                dp[i1][j2] = min(dp[i1-1][j2], dp[i1][j2-1])+grid[i1][j2];
            }
        }
        
        return dp[m-1][n-1];
    }
};

Search

    Table of Contents