zoukankan      html  css  js  c++  java
  • 64. Minimum Path Sum

    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:

    Input:
    [
      [1,3,1],
      [1,5,1],
      [4,2,1]
    ]
    Output: 7
    Explanation: Because the path 1→3→1→1→1 minimizes the sum.
    
    Accepted
    272,029
    Submissions
    553,230
     
    遍历的练手题,说是dp,其实跟暴力运算差不多了, 只是把暴力运算的中间结果存起来 ,空间换时间;
    提交的时候提示那个faster than xx% 其实不准, 这题本来就比较耗时间, 纯遍历, O(m*n), 但实际程序运行的时候还要考虑cpu调度,内存分配等问题,与理论值相去甚远.
    class Solution {
    public:
        int minPathSum(vector<vector<int>>& grid) {
            if(grid.empty()||grid[0].empty()) return 0;
            int h=grid.size(),w=grid[0].size();
            vector<vector<int>> dp(h,vector<int>(w));
            for(int i=0;i<h;++i)
                for(int j=0;j<w;++j)
                {
                    if(0==i&&0==j) dp[i][j]=grid[i][j];
                    else if (0==i&&j) dp[i][j]=dp[i][j-1]+grid[i][j];
                    else if(0==j&&i) dp[i][j]+=dp[i-1][j]+grid[i][j];
                    else dp[i][j]+=min(dp[i-1][j],dp[i][j-1])+grid[i][j];
                }
            return dp[h-1][w-1];
        }
    };
  • 相关阅读:
    G a+b+c+d=?
    H Kuangyeye and hamburgers
    python 实现加法
    高精度板子
    angular项目一
    angular大牛的博客
    autocomplete
    angular的 表单
    快捷方式控制台调试each这种方法的时候怎么停
    自己练习的一些应该熟记的代码
  • 原文地址:https://www.cnblogs.com/lychnis/p/11743120.html
Copyright © 2011-2022 走看看