[leetcode] Minimum Path Sum


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.

tag: array, dynamic programming

巧了,和上到题,Edit Distance惊人的相似,稍微改了下代码(转移规则)就AC了。

C++:

class Solution {
public:
    int minPathSum(vector<vector<int> > &grid) {
        int m = grid.size();
        int n = grid[0].size();
        
        int costMap[m][n];
        
        //initialize costMap
        costMap[0][0] = grid[0][0];
        for(int i = 1; i < m ; i++){
            costMap[i][0] = costMap[i-1][0] + grid[i][0];
        }
        for(int i = 1; i < n; i++){
            costMap[0][i] = costMap[0][i-1] + grid[0][i];
        }
        
        for (int i = 1; i < m; i++){
            for (int j = 1; j < n; j++){
                costMap[i][j] = min(costMap[i-1][j], costMap[i][j-1]) + grid[i][j];
            }
        }
        return costMap[m-1][n-1];
    }
};

Selection_008

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.