题目:
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.
分析:
矩阵,左上角到右下角,寻找最短路径。
思路:
典型的动态规划题目。s(i, j) = min(s(i - 1, j), s(i, j-1)) + s(i, j).但要特别注意临界条件。
代码:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int min = -1;
int rowLen = grid.size();
int colLen = grid[0].size();
int small;
for(int i = 0; i< rowLen; i++)
{
for(int j = 0; j< colLen; j ++)
{
small = 0;
if(j == 0 && i!= 0) small = grid[i -1][j];
if(i == 0 && j != 0) small = grid[i][j-1];
if(i != 0 && j != 0)
{
small = grid[i-1][j];
if(grid[i-1][j] > grid[i][j -1]) small = grid[i][j-1];
}
if(i == rowLen -1 && j == colLen -1)
{
if(min < 0 || min > grid[i][j] + small) min = grid[i][j] + small;
}
else
{
grid[i][j] = grid[i][j] + small;
}
}
}
return min;
}
};
先处理好临界条件,在进行循环处理:
参考代码:
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
if(!grid.size())return 0;
const int rows=grid.size(),cols=grid[0].size();
// r[i] == min path sum to previous row's column i.
vector<int> r(cols,0);
int i,j;
r[0]=grid[0][0];
for(j=1;j<cols;j++){
r[j]=grid[0][j]+r[j-1];
}
for(i=1;i<rows;i++){
r[0]+=grid[i][0];
for(j=1;j<cols;j++){
r[j]=min(r[j-1],r[j])+grid[i][j];
}
}
return r[cols-1];
}
};