题目
Total Accepted: 47928 Total Submissions: 148011 Difficulty: Medium
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.
分析
这道题目是求最小路径和,与LeetCode 62以及LeetCode63本质相同,只需要把存储路径数目的数组改为存储当前最小路径和即可。
AC代码
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if (grid.empty())
return 0;
//求当前矩阵的行数、列数
int m = grid.size();
int n = grid[0].size();
vector<vector<int> > sum(m, vector<int>(n, 0));
//记录首元素和
sum[0][0] = grid[0][0];
int minSum = sum[0][0];
for (int i = 1; i < m; i++)
{
sum[i][0] = sum[i - 1][0] + grid[i][0];
//此时路径和唯一,也是最小路径和
}//for
for (int j = 1; j < n; j++)
{
sum[0][j] = sum[0][j - 1] + grid[0][j];
//此时路径和唯一,也是最小路径和
}//for
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];
}//for
}//for
return sum[m - 1][n - 1];
}
};