首页 > 其他 > 详细

[LeetCode]Minimum Path Sum

时间:2016-03-23 21:55:00      阅读:267      评论:0      收藏:0      [点我收藏+]

题目描述:

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

原文:http://www.cnblogs.com/skycore/p/5312866.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!