[leetcode] 64. Minimum Path Sum

题目:

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.

Example:

Input:
[
  [1,3,1],
  [1,5,1],
  [4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.

代码:

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        vector<int> dp(grid[0].size(), 0);
        for(int i = 0; i < grid.size(); i++){
            for(int j = 0; j < grid[0].size(); j++){
                if(i == 0 && j == 0) dp[0] = grid[0][0];
                else if(i != 0 && j == 0) dp[j] = dp[j] + grid[i][j];
                else if(i == 0 && j != 0) dp[j] = dp[j-1] + grid[0][j];
                else{
                    dp[j] = min(dp[j], dp[j-1]) + grid[i][j];
                }
            }
        }
        return dp[grid[0].size()-1];
    }
};

猜你喜欢

转载自blog.csdn.net/jing16337305/article/details/80766747