LeetCode (Minimum Path Sum)

来源:互联网 发布:怎样做淘宝客赚钱手机 编辑:程序博客网 时间:2024/06/06 00:38

Problem:

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.

Solution:

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


0 0
原创粉丝点击