64. Minimum Path Sum

来源:互联网 发布:道路照明计算软件 编辑:程序博客网 时间:2024/06/17 03:26

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 1:
[[1,3,1],
[1,5,1],
[4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.

class Solution {public:    int minPathSum(vector<vector<int>>& grid) {        size_t rows = grid.size();        if (rows == 0) return 0;        size_t cols = grid[0].size();        vector<int> p(rows);        p[0] = grid[0][0];        for (size_t i = 1; i != rows; ++i)             p[i] = p[i - 1] + grid[i][0];         for (size_t i = 1; i != cols; ++i) {            p[0] = p[0] + grid[0][i];                        for (size_t j = 1; j != rows; ++j) {                    p[j] = min(p[j - 1], p[j]) + grid[j][i];            }        }        return p[rows - 1];     }};
原创粉丝点击