[LeetCode]Minimum Path Sum

Posted skycore

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]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.

解题思路:

动态规划,算出所有位置到起点的最小距离

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

 

以上是关于[LeetCode]Minimum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章

leetcode:Minimum Path Sum

LeetCode OJ 64. Minimum Path Sum

[LeetCode] 64. Minimum Path Sum

Leetcode64 Minimum Path Sum

Leetcode64 Minimum Path Sum

[leetcode] Minimum Path Sum