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

Minimum Path Sum

时间:2014-08-25 20:41:44      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   strong   for   div   log   

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.

思路:使用动态规划求解即可。dist[i][j]记录从左上角到达坐标(i-1,j-1)的距离,则dist[i][j] = grid[i-1][j-1] + min( dist[i-1][j], dist[i][j-1] )。

 1 class Solution {
 2 public:
 3     int minPathSum( vector<vector<int>> &grid ) {
 4         if( grid.empty() || grid[0].empty() ) { return 0; }
 5         int rows = grid.size(), cols = grid[0].size();
 6         vector<vector<int>> dist( rows+1, vector<int>( cols+1, INT_MAX ) );
 7         dist[0][1] = dist[1][0] = 0;
 8         for( int i = 1; i <= rows; ++i ) {
 9             for( int j = 1; j <= cols; ++j ) {
10                 dist[i][j] = grid[i-1][j-1] + min( dist[i-1][j], dist[i][j-1] );
11             }
12         }
13         return dist[rows][cols];
14     }
15 };

 

Minimum Path Sum

标签:style   blog   color   使用   io   strong   for   div   log   

原文地址:http://www.cnblogs.com/moderate-fish/p/3935283.html

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