【Leetcode】【Medium】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.

解题思路:

Unique Paths题目非常类似,区别在于本题为有权值路径;

解题方法基本一致,还是通过数组迭代方法,使用n个额外空间的动态规划思路,区别在于迭代前需要计算数组初始值。

代码:

 1 class Solution {
 2 public:
 3     int minPathSum(vector<vector<int>>& grid) {
 4         int m = grid.size();
 5         int n = grid[0].size();
 6         vector<int> col(grid.back());
 7         
 8         for (int i = n - 2; i >= 0; --i) 
 9             col[i] += col[i+1];
10         
11         for (int i = m - 2; i >= 0; --i) {
12             col[n-1] += grid[i][n-1];
13             for (int j = n - 2; j >= 0; --j) {
14                 col[j] = grid[i][j] + min(col[j], col[j+1]);
15             }
16         }
17         
18         return col[0];
19     }
20 };
原文地址:https://www.cnblogs.com/huxiao-tee/p/4298442.html