lintcode-110-最小路径和
110-最小路径和
给定一个只含非负整数的m*n网格,找到一条从左上角到右下角的可以使数字和最小的路径。
注意事项
你在同一时间只能向下或者向右移动一步
样例
标签
动态规划
思路
使用动态规划,用二维数组 dp[i][j] 表示网格第 i 行、第 j 列元素到右下角的最小路径
动态转移方程为:dp[i][j] = gird[i][j] + min(dp[i+1][j], dp[i][j+1])
过程如下图
code
class Solution {
public:
/**
* @param grid: a list of lists of integers.
* @return: An integer, minimizes the sum of all numbers along its path
*/
int minPathSum(vector<vector<int> > &grid) {
// write your code here
int sizeRow = grid.size(), sizeCol = grid[0].size(), i = 0, j = 0;
if(sizeRow <= 0) {
return 0;
}
vector<vector<int> > dp(sizeRow, vector<int>(sizeCol, 0x7FFFFFFF));
for(i=sizeRow-1; i>=0; i--) {
for(j=sizeCol-1; j>=0; j--) {
if(i == sizeRow-1 && j == sizeCol-1) {
dp[i][j] = grid[i][j];
}
else if(i == sizeRow-1 && j < sizeCol-1) {
dp[i][j] = grid[i][j] + dp[i][j+1];
}
else if(i < sizeRow-1 && j == sizeCol-1) {
dp[i][j] = grid[i][j] + dp[i+1][j];
}
else if(i < sizeRow-1 && j < sizeCol-1) {
dp[i][j] = grid[i][j] + ((dp[i+1][j] > dp[i][j+1]) ? dp[i][j+1] : dp[i+1][j]);
}
}
}
return dp[0][0];
}
};