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

leetcode No64. Minimum Path Sum

时间:2016-08-02 21:09:19      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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.

Algorithm:

比较从左边来的路径和和从上面来的路径谁小,再加上当前元素,还是用动态规划

Accepted Code:

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int M=grid.size();
        int N=grid[0].size();
        if(M==0) return 0;
        vector<vector<int>> res(grid);
        for(int j=1;j<N;j++)    //先要把边界的算出来
            res[0][j]+=res[0][j-1];
        for(int i=1;i<M;i++)
            res[i][0]+=res[i-1][0];
        for(int i=1;i<M;i++)
            for(int j=1;j<N;j++)
            {
                res[i][j]=min(res[i-1][j],res[i][j-1])+res[i][j];
            }
        return res[M-1][N-1];
    }
};


leetcode No64. Minimum Path Sum

标签:

原文地址:http://blog.csdn.net/u011391629/article/details/52097867

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