标签: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 };
标签:style blog color 使用 io strong for div log
原文地址:http://www.cnblogs.com/moderate-fish/p/3935283.html