原题:
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的问题,从(0,0)点出发,到达(m-1, n-1)点,每次选择的时候都是依据上一次的结果推断后做累加。
dp[i][j] = (dp[i-1][j] > dp[i][j-1] ?
dp[i][j-1] : dp[i-1][j]) + grid[i][j];
选择最小的值来更新当前的结果。
能够AC的C++代码例如以下:
int minPathSum(vector<vector<int>>& grid) {
if(grid.size() < 1 || grid[0].size() < 1)
return -1;
int m = grid.size(), n = grid[0].size();
int **dp = new int*[m];
for(int i=0; i<m; i++){
dp[i] = new int[n];
memset(dp[i], 0, sizeof(int) * n);
}
dp[0][0] = grid[0][0];
for(int i=1; i<m; i++){
dp[i][0] = dp[i-1][0] + grid[i][0];
}
for(int i=1; i<n; i++){
dp[0][i] = dp[0][i-1] + grid[0][i];
}
for(int i=1; i<m; i++){
for(int j=1; j<n; j++){
dp[i][j] = (dp[i-1][j] > dp[i][j-1] ? dp[i][j-1] : dp[i-1][j]) + grid[i][j];
}
}
return dp[m-1][n-1];
}