问题描述:
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.
分析:和上两道题一样,这个也是使用DP算法,比较简单。
代码如下:20ms
int minPathSum(int** grid, int gridRowSize, int gridColSize) {
int row,col;
int *nums = (int *)malloc(sizeof(int)*gridColSize);
row = gridRowSize-1;
col = gridColSize-1;
nums[col] = grid[row][col];
for(--col;col>=0;col--){
nums[col] = grid[row][col] + nums[col+1];
}
for(row = gridRowSize-2;row>=0;row--){
for(col = gridColSize-1;col>=0;col--){
int right = 10000000;
if(col+1<gridColSize)
right = nums[col+1];
int offset = (right<nums[col])?right:nums[col];
nums[col] = grid[row][col]+offset;
}
}
return nums[0];
}