Minimum Path Sum

LeetCode #64


Description:

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:

Note

Idea:

DP思想

DP[i][j] = grid[i][j] + min(DP[i-1][j], DP[i][j-1]);

Code:

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();

        vector<vector<int>> DP(m, vector<int>(n, 0));

        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(i==0 && j==0) DP[i][j] = grid[i][j];
                else if(i==0) DP[i][j] = grid[i][j] + DP[i][j-1];
                else if(j==0) DP[i][j] = grid[i][j] + DP[i-1][j];
                else DP[i][j] = grid[i][j] + min(DP[i-1][j], DP[i][j-1]);
            }
        }

        return DP[m-1][n-1];

    }
};

results matching ""

    No results matching ""