Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
29 lines (25 sloc) 983 Bytes
problem:
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.
-------------------------------------------------------------------
solution:
//动态规划实现
//对每个点,到这个点的路径要么从上方要么从左方
//特殊的,对于[0][j]的点只考虑从左方来,[i][0]的点只考虑从上方来
int minPathSum(vector<vector<int> > &grid)
{
int m = grid.size();
int n = grid[0].size();
if(m == 0 || n == 0)
return 0;
int pathSum[m][n];
pathSum[0][0] = grid[0][0];
for(int i = 1; i < m; ++i)
pathSum[i][0] = pathSum[i - 1][0] + grid[i][0];
for(int j = 1; j < n; ++j)
pathSum[0][j] = pathSum[0][j - 1] + grid[0][j];
for(int i = 2; i < m; ++i)
for(int j = 2; j < n; ++j)
pathSum[i][j] = min(pathSum[i - 1][j], pathSum[i][j - 1])+ grid[i][j];
return pathSum[m - 1][n - 1];
}