之所以将这三道题放在一起,是因为这三道题非常类似。

  1. 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.

  该题解答参考自一博文

  设dp[i][j]表示从左上角到grid[i][j]的最小路径和。那么dp[i][j] = grid[i][j] + min( dp[i-1][j], dp[i][j-1] );

  下面的代码中,为了处理计算第一行和第一列的边界条件,我们令dp[i][j]表示从左上角到grid[i-1][j-1]的最小路径和,最后dp[rows][cols]是我们所求的结果

 1 int minPathSum(vector<vector<int>>& grid) {
 2     int rows = grid.size();
 3     if(rows == 0)
 4         return 0;
 5     int cols = grid[0].size();
 6     
 7     vector<vector<int> > dp(rows + 1, vector<int>(cols + 1, INT_MAX));
 8     dp[0][1] = 0;
 9     for(int i = 1; i < rows + 1; i++)
10         for(int j = 1; j < cols + 1; j++)
11             dp[i][j] = grid[i - 1][j - 1] + min(dp[i][j - 1], dp[i - 1][j]);
12     
13     return dp[rows][cols];
14 }
View Code 

相关文章:

  • 2021-09-18
  • 2022-02-04
  • 2022-01-04
  • 2021-09-15
  • 2021-07-21
  • 2021-10-17
  • 2021-08-27
猜你喜欢
  • 2021-07-16
  • 2021-08-26
  • 2021-12-23
  • 2021-10-20
  • 2022-12-23
  • 2021-05-21
  • 2022-02-20
相关资源
相似解决方案