64. Minimum Path Sum

题目

  • 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:

    1
    2
    3
    4
    5
    6
    7
    8
    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 x n格中左上角到右下角路径的最小距离,并且没有负权值
  • dp[i][j]:起点到点 [i,j]的最小距离
  • 因为没有负路径和寻路方向只能向下或者向右,因此对于每个点(除起点),其dp[i][j]的表示为 dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j]

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int minPathSum(vector<vector<int> >& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int> > dp(m, vector<int>(n, 0));
dp[0][0] = grid[0][0];
for(int i = 0; i < m; ++i)
for(int j = 0; j < n ; ++j) {
if(i == 0 && j == 0) continue;
if(i == 0)
dp[i][j] = dp[i][j-1] + grid[i][j];
else if(j == 0)
dp[i][j] = dp[i-1][j] + grid[i][j];
else
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}

return dp[m-1][n-1];
}
};