码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode64 Minimum Path Sum

时间:2016-09-20 22:38:01      阅读:173      评论: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.(Medium)

分析:

矩阵型动态规划,dp[i][j]表示到达i,j位置的。。。。

所以本题中dp[i][j]表示到达grid[i][j]的最小和。dp[i][j] = dp[i -1][j] + dp[i][j - 1];

代码:

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

 

LeetCode64 Minimum Path Sum

标签:

原文地址:http://www.cnblogs.com/wangxiaobao/p/5890673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!