题目链接: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.

这道题的要求是在m*n的网格中找到从左上角到右下角的和最小的路径。每次只能向下或者向右移动1格。

这是动态规划的问题,由于每次只能向下或者向右移动,因此[i, j]位置时的最小路径的和等于[i, j-1]和[i-1, j]中较小的加上[i, j]位置的数值。因此递推公式是grid[i][j] += min(grid[i][j-1], grid[i-1][j])。

时间复杂度:O(mn)

空间复杂度:O(mn)

 1 class Solution
 2 {
 3 public:
 4     int minPathSum(vector<vector<int> > &grid)
 5     {
 6         
 7         if(grid.size() == 0 || grid[0].size() == 0)
 8             return 0;
 9         
10         for(int i = 0; i < grid.size(); ++ i)
11             for(int j = 0; j < grid[i].size(); ++ j)
12             {
13                 if(i == 0 && j == 0) // 左上角的点不做处理
14                     continue;
15                 else if(i == 0) // 处理左面边界
16                     grid[i][j] += grid[i][j - 1];
17                 else if(j == 0) // 处理上面边界
18                     grid[i][j] += grid[i - 1][j];
19                 else
20                     grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]);
21             }
22         
23         return grid[grid.size() - 1][grid[0].size() - 1];
24     }
25 };