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:
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
给定一个(m*n)的网格,其中填充非负数,寻找一条从左上角到右下角的路径,使沿路径上的所有数字的总和最小。
这是一个典型的动态规划问题,假设到达点(i,j)的最小路径和为S[i][j],那么S[i][j] = min(S[i][j-1],S[i-1][j])+grid[i][j]
S[i][j-1]表示到达点(i,j-1) (这个点位于(i,j)的左边)的最小路径和
S[i-1][j]表示到达点(i-1,j) (这个点位于(i,j)的上方)的最小路径和
一些边界条件需要处理。边界条件发生在最顶行(S [i -1] [j]不存在),最左边的列(S [i] [j - 1]不存在)
class Solution {
public:
int minPathSum(vector>& grid) {
int m = grid.size(); //表示共有多少行
int n = grid[0].size();//表示共有多少列
vector > sum(m, vector(n, grid[0][0]));
//创建了一个名为sum的矩阵(m行,n列,每个值都是 grid[0][0])
for (int i = 1; i < m; i++)
sum[i][0] = sum[i - 1][0] + grid[i][0];
//sum的第一列求出
for (int j = 1; j < n; j++)
sum[0][j] = sum[0][j - 1] + grid[0][j];
//sum的第一行求出
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
sum[i][j] = min(sum[i - 1][j], sum[i][j - 1]) + grid[i][j];
return sum[m - 1][n - 1];
}
};
for (int i = 1; i < m; i++)
sum[i][0] = sum[i - 1][0] + grid[i][0];
//sum的第一列求出
求出最小路径和的第一列:
[ [
[1,3,1], [1,1,1],
[1,5,1], 以这个矩阵为例 for循环之心发完毕后为: [2,1,1],
[4,2,1] [6,1,1]
] ]
for (int j = 1; j < n; j++)
sum[0][j] = sum[0][j - 1] + grid[0][j];
//sum的第一行求出
求出最小路径和的第一行:
[ [
[1,1,1], [1,4,5],
[2,1,1], 以这个矩阵为例 for循环之心发完毕后为:[2,1,1],
[6,1,1] [6,1,1]
] ]
sum[1][1] = min(sum[0][1],sum[1][0]) + grid[1][1] = min(4,2) + 5 = 2 + 5 =7
sum[1][2] = min(sum[0][2],sum[1][1]) + grid[1][2] = min(5,7) + 1 = 5 + 1 =6
sum[2][1] = min(sum[1][1],sum[2][0]) + grid[2][1] = min(7,6) + 2 = 6 + 2 =8
sum[2][2] = min(sum[1][2],sum[2][1]) + grid[2][2] = min(6,8) + 1 = 6 + 1 =8
[
[1,4,5],
sum = [2,7,6],
[6,8,7]
]
(待续……)