zoukankan      html  css  js  c++  java
  • 【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();
        }
    };
  • 相关阅读:
    5.Docker服务进程关系
    朴素贝叶斯知识点概括
    k近邻法(KNN)知识点概括
    机器学习的应用实例
    HNU 10111 0-1矩阵
    CSU 1421 Necklace
    Poj 3469 Dual Core CPU
    Poj 2135 Farm Tour
    Poj 3180 The Cow Prom
    HDU 1004 Let the Balloon Rise
  • 原文地址:https://www.cnblogs.com/dplearning/p/4153597.html
Copyright © 2011-2022 走看看