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

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.

分析

这道题直接用dp,状态转移方程也容易找出来

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

压缩一下空间

const int inf=999999;
class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m=grid.size(),n=grid[0].size();
        vector<int> dp(n+1,inf);
        dp[1]=0;
        for(int i=1;i<=m;i++)
            for(int j=1;j<=n;j++)
                dp[j]=min(dp[j],dp[j-1])+grid[i-1][j-1];
        return dp[n];
    }
};
posted @ 2018-11-29 22:00  A-Little-Nut  阅读(103)  评论(0编辑  收藏  举报