leetcode:Minimum Path Sum(路线上元素和的最小值)【面试算法题】

时间:2021-05-15 16:49:31

题目:

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每个状态由左边或者上边的值中,较小的值与当前状态的值相加得到。

注意考虑边界情况就行了。

int dp[1000][1000];
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
int rows=grid.size();
if(rows==0)return 0;
int cols=grid[0].size();
if(cols==0)return 0;
memset(dp,0,sizeof(dp));
for(int i=0;i<rows;++i)
{
for(int j=0;j<cols;++j)
{
if(i==0&&j==0)dp[0][0]=grid[0][0];
else if(j==0)dp[i][0]=dp[i-1][0]+grid[i][0];
else if(i==0)dp[0][j]=dp[0][j-1]+grid[0][j];
else dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid[i][j];
}
}
return dp[rows-1][cols-1];
}
};