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

Minimum Path Sum

时间:2015-06-17 00:25:03      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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.

Code:

 int minPathSum(vector<vector<int>>& grid) {
       int m = grid.size();
       assert(0!=m);
       int n = grid[0].size();
       assert(0!=n);
       
//pathSum[i][j]表示从元素(i,j)到元素(m-1,n-1)即右下角的路径和
       vector<vector<int>>pathSum(grid);
       for (int i = n-2; i >=0; --i)
            pathSum[m-1][i] += pathSum[m-1][i+1];
       for (int i = m-2; i >=0; --i)
            pathSum[i][n-1] += pathSum[i+1][n-1];
            
       for (int i = m-2; i >= 0; --i)
       {
           for (int j = n-2; j >= 0; --j)
           {
                    pathSum[i][j] += min(pathSum[i+1][j], pathSum[i][j+1]);
           }
       }
       return pathSum[0][0];
    }

 

Minimum Path Sum

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4582147.html

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