64. Minimum Path Sum Add to List
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.
题目: 给定一个m*n的格栏,格栏中的元素非负,找到一条从左上角到右下角的路径,这条路径使得路径上的和最小。每一次只能下移或者右移。
我觉得,其实这题可以采用最长公共子序列一样方法,使用动态规划解决。在最长公共子序列中,给定两个字符串a和b,我们使用c[i][j]表示当前最长公共子序列的长度,动态转移方法为:
因为格栏中的元素非负,这样保证了路径和只能不断的往上加,那么我们只需要保证当前时刻的路径和最小,就能保证最后得到的路径和最小。因此同样的,在这道题中我们可以使用c[i][j]表示当前最小的路径和。那么对于第一列上的c[i][j], 其路径和只能是上一行来的;对于第一行的c[i][j],其路径和只能是从前一列来的。而对于其他的c[i][j],则是由c[i-1][j]和c[i][j-1]中小的那个来的。因此,动态转移方程为:
c[i][j]=⎧⎩⎨⎪⎪c[i−1][j]+grid[i][j]c[i][j−1]+grid[i][j]min(c[i−1][j],c[i][j−1])+grid[i][j]if j == 0if i == 0else
实现代码如下:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int nrows = grid.size();
int ncols = grid[0].size();
int sums[nrows][ncols];
sums[0][0] = grid[0][0];
for (int i = 1; i < nrows; i++) sums[i][0] = sums[i-1][0] + grid[i][0];
for (int j = 1; j < ncols; j++) sums[0][j] = sums[0][j-1] + grid[0][j];
for (int i = 1; i < nrows; ++i)
{
for (int j = 1; j < ncols; ++j)
{
sums[i][j] = min(sums[i][j-1], sums[i-1][j]) + grid[i][j];
}
}
return sums[nrows-1][ncols-1];
}
};