首页 > 代码库 > 【leetcode】Minimum Path Sum(easy)

【leetcode】Minimum Path Sum(easy)

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.

 

思路:由于只能向两个方向走,瞬间就没有了路线迂回的烦恼,题目的难度大大的降低了。先得到到达最上边和最左边的最小路径,其他的就从上面点和左边点中选一个路径短的路径加上。

当然,也可以空间上更简单一些,只缓存一行的数据,然后一行行的更新。但我懒得写了...

#include <iostream>#include <vector>#include <algorithm>#include <queue>#include <stack>using namespace std;class Solution {public:    int minPathSum(vector<vector<int> > &grid) {        if(grid.size() == 0)        {            return 0;        }        vector<vector<int> > ans(grid.size(), vector<int>(grid[0].size(), 0));        ans[0][0] = grid[0][0];        for(int i = 1; i < grid.size(); i++)        {            ans[i][0] = ans[i - 1][0] + grid[i][0];        }        for(int j = 1; j < grid[0].size(); j++)        {            ans[0][j] = ans[0][j - 1] + grid[0][j];        }        for(int i = 1; i <grid.size(); i++)        {            for(int j = 1; j <grid[0].size(); j++)            {                ans[i][j] = min(ans[i - 1][j], ans[i][j - 1]) + grid[i][j];            }        }        return ans.back().back();    }};

 

【leetcode】Minimum Path Sum(easy)