LeetCode-minimum-path-sum

Question

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

1、动态规划。 p[i][j] = grid[i][j] + min(p[i - 1][j], p[i][j - 1]). 因为到达一个节点,最多有两种选择,当然是选择代价较小的。

2、时间复杂度O(n^2)。

#include<iostream>
#include<vector> //std::vector
#include<algorithm> //std::min
using namespace std;
class Solution
{
public:
    //注意,这里二维向量<>里面要加一个空格,编译报了莫名其妙的错误。
    int minPathSum(vector<vector<int> > &grid)
    {
        if(grid.size() < 0)
            return 0;
        vector<vector<int> > table(grid.size(), vector<int>(grid[0].size(),0));
        int row = grid.size();
        int column = grid[0].size();
        table[0][0] = grid[0][0];

        //将gird的第一列累加,存储到table中。
        for(int i = 1; i < row; i++)
        {
            table[i][0] = grid[i][0] = grid[i - 1][0];
        }
        //将gird的第一行累加,存储到table中。
        for(int j = 1; j < column; j++)
        {
            table[0][j] = grid[0][j] = grid[0][j - 1];
        }
        //遍历gird的剩余点
        //因为到达一个节点,最多有两种选择,当然是选择代价较小的。
        for(int i = 1; i < row; i++)
            for(int j = 1; j < column; j++)
                table[i][j] = grid[i][j] + min(grid[i - 1][j],grid[i][j - 1]);
        return table[row - 1][column - 1];
    }
};

参考:学习博客
参考:min函数官方文档

猜你喜欢

转载自blog.csdn.net/qq_29611345/article/details/81051494