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 minimizes the sum of all numbers along its path.

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

解题思路:动态规划,p[i][j]表示从grid[0][0]到grid[i][j]的最小距离。p[i][j] = min(p[i-1][j] , p[i][j-1]) + grid[i][j]

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        if(!grid.size()) return 0;
        int m = grid.size(), n = grid[0].size();
        int p[m][n];
        p[0][0] = grid[0][0];
        for(int i=1 ;i<m;i++){
            p[i][0]=p[i-1][0]+grid[i][0];
        }
        for(int j=1; j<n;j++){
            p[0][j]=p[0][j-1]+grid[0][j];
        }
        for(int i=1; i<m; i++){
            for(int j=1; j<n; j++){
                p[i][j] = min(p[i][j-1],p[i-1][j])+grid[i][j];
            }
        }
        return p[m-1][n-1];
    }
};


你可能感兴趣的:(LeetCode,dp)