首页 > 其他 > 详细

【LeetCode】Minimum Path Sum

时间:2014-08-31 19:59:31      阅读:271      评论:0      收藏:0      [点我收藏+]

Minimum Path Sum

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.

 

解题思路:

典型的动态规划。开辟m*n的矩阵minV,minV[i][j]存放从首元素(grid[0][0])到当前元素(grid[i][j])的最短路径长度。

对于每个元素来说,路径是从上或者从左边来的。

也就是说minV[i][j] = min(minV[i-1][j]+minV[i][j-1]) + grid[i][j]。

别忘了初始化第一行第一列。

 

class Solution 
{
public:
    int minPathSum(vector<vector<int> > &grid) 
    {
        int m = grid.size();
        int n = grid[0].size();

        //DP,存放从首元素到该元素的最短路径
        vector<vector<int> > minV;
        minV.resize(m);
        for(vector<vector<int> >::size_type st = 0; st < m; st ++)
            minV[st].resize(n);

        minV[0][0] = grid[0][0];

        //第一列初始化
        for(vector<vector<int> >::size_type st = 1; st < m; st ++)
            minV[st][0] = minV[st-1][0] + grid[st][0];

        //第一行初始化
        for(vector<int>::size_type st = 1; st < n; st ++)
            minV[0][st] = minV[0][st-1] + grid[0][st];

        for(vector<vector<int> >::size_type st1 = 1; st1 < m; st1 ++)
        {
            for(vector<int>::size_type st2 = 1; st2 < n; st2 ++)
            {
                minV[st1][st2] = min(minV[st1-1][st2],minV[st1][st2-1])+grid[st1][st2];
            }
        }

        return minV[m-1][n-1];
    }
};

bubuko.com,布布扣

【LeetCode】Minimum Path Sum

原文:http://www.cnblogs.com/ganganloveu/p/3948069.html

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