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

LeetCode:Minimum Path Sum

时间:2014-12-26 11:12:15      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   

题目描述:

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.


思路:采用动态规划的方法,用数组存储起点到当前点距离的最小值。首先算出第一行和第一列的最小值,然后用公式grid[i][j]=grid[i][j] + min(grid[i-1][j],grid[i][j-1])算出其余点的最小值,即可得结果。


代码:

int Solution::minPathSum(vector<vector<int> > &grid)
{
    int m = grid.size();
    int n = grid[0].size();
    int i,j;
    for(i = 1;i < m;i++)
        grid[i][0] = grid[i-1][0] + grid[i][0];
    for(j = 1;j < n;j++)
        grid[0][j] = grid[0][j-1] + grid[0][j];
    for(i = 1;i < m;i++)
        for(j = 1;j < n;j++)
            grid[i][j] = grid[i][j] + min(grid[i-1][j],grid[i][j-1]);
    return grid[m-1][n-1];
}


LeetCode:Minimum Path Sum

标签:algorithm   leetcode   

原文地址:http://blog.csdn.net/yao_wust/article/details/42168279

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