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:
First Version:void helper(vector<vector<int> > &grid, int m, int n, int& max, int cur) { if(m<=grid.size()-1&&n<=grid[0].size()-1) { cur+=grid[m][n]; if(m==grid.size()-1&&n==grid[0].size()-1&&cur<max) max = cur; helper(grid, m, n+1, max, cur); helper(grid, m+1, n, max,cur); } else return; } int minPathSum(vector<vector<int> > &grid) { int max = INT_MAX; if(grid.size()==0) return 0; int cur = 0; helper(grid, 0,0,max,cur); return max; }
Second Version:
int minPathSum(vector<vector<int> > &grid) {
if(grid.size()==0)
return 0;
int row = grid.size();
int column = grid[0].size();
vector<int> cur(column, INT_MAX);
cur[0] = 0;
for(int i=0;i<row;i++)
{
cur[0] = cur[0]+grid[i][0];
for(int j=1;j<column;j++)
{
cur[j] = min(cur[j], cur[j-1])+grid[i][j];
}
}
return cur[column-1];
}
No comments:
Post a Comment