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

leetcode - Minimum Path Sum

时间:2015-09-14 15:20:05      阅读:125      评论: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.

//利用dp解决,动态转移方程为:
// dp[i][j] = min(dp[i-1][j],dp[i][j-1]) + grid[i][j].
class Solution {
public:
    int minPathSum(std::vector<std::vector<int> > &grid) {
        std::vector<std::vector<int>> dp(grid.size(),std::vector<int>(grid[0].size(),0));
		dp[0][0] = grid[0][0];

		for (int i = 1; i < grid.size(); i++)
		{
			dp[i][0] = dp[i-1][0] + grid[i][0];
		}
		for (int i = 1; i < grid[0].size(); i++)
		{
			dp[0][i] = dp[0][i-1] + grid[0][i];
		}
		for (int i = 1; i < grid.size(); i++)
		{
			for (int j = 1; j < grid[0].size(); j++)
			{
				dp[i][j] = std::min(dp[i-1][j],dp[i][j-1]) + grid[i][j];
			}
		}
		return dp[grid.size()-1][grid[0].size()-1];
    }
};


版权声明:本文博主原创文章,博客,未经同意不得转载。

leetcode - Minimum Path Sum

标签:

原文地址:http://www.cnblogs.com/hrhguanli/p/4807012.html

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