[LeetCode] 057: Minimum Path Sum

来源:互联网 发布:好看的网络自制剧 编辑:程序博客网 时间:2024/05/17 08:40
[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]
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// empty
if(grid.size() == 0 || grid[0].size() == 0)return 0;

// initial
int **dp = new int*[grid.size()];
for(int i = 0; i < grid.size(); ++i){
dp[i] = new int[grid[i].size()];
}

// dp
for(int i = 0; i < grid.size(); ++i){
for(int j = 0; j < grid[i].size(); ++j){
if(i == 0 && j == 0){
dp[i][j] = grid[i][j];
}
else if(i == 0){
dp[i][j] = dp[i][j-1] + grid[i][j];
}
else if(j == 0){
dp[i][j] = dp[i-1][j] + grid[i][j];
}
else{
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
}
}
return dp[grid.size()-1][grid[grid.size()-1].size()-1];
}
};
说明:版权所有,转载请注明出处。Coder007的博客