64. Minimum Path Sum / minimum path and

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.

AC Code

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

to sum up

Dynamic programming ideas consistent with the title, will read short int can reduce memory consumption

Guess you like

Origin blog.csdn.net/weixin_34240520/article/details/91028549