【LeetCode】64. 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.

 

解题思路:

典型的动态规划。开辟m*n的矩阵path,path[i][j]存放从首元素(grid[0][0])到当前元素(grid[i][j])的最短路径长度。

对于每个元素来说,路径是从上或者从左边来的。

也就是说path[i][j] = min(path[i-1][j]+path[i][j-1]) + grid[i][j]。

注意:初始化第一行第一列。

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

你可能感兴趣的:(LeetCode)