Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode_64_Minimum Path Sum #19

Open
lihe opened this issue Nov 9, 2019 · 0 comments
Open

Leetcode_64_Minimum Path Sum #19

lihe opened this issue Nov 9, 2019 · 0 comments
Labels

Comments

@lihe
Copy link
Owner

lihe commented Nov 9, 2019

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.

解题思路:

  1. dp[i][j]是到达(i,j)时的最优解;
  2. dp[i, j] = min(dp[i-1][j], dp[i][j-1]) + grid(i,j)
class Solution{
public:
    int minPathSum(std::vector<std::vector<int>> &grid){
        if(grid.size() == 0){
            return 0;
        }
        int row = grid.size();
        int column = grid[0].size();
        std::vector<std::vector<int>> dp(row, std::vector<int>(column, 0));

        dp[0][0] = grid[0][0];
        for(int i = 1; i < column; i++){
            dp[0][i] = dp[0][i - 1] + grid[0][i];
        }
        for(int i = 1; i < row; i++){
            dp[i][0] = dp[i - 1][0] + grid[i][0];
            for(int j = 1; j < column; j++){
                dp[i][j] = std::min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }
        return dp[row - 1][column - 1];
    }
};
@lihe lihe added the Leetcode label Nov 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant