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];
        }
    };
  • 相关阅读:
    iOS 11 application 新特性
    Swift循环遍历集合方法
    Swift 使用 #warning
    swift 3.0 正则表达式查找/替换字符
    App Store 审核指南
    iOS 获取设备的各种信息的方法
    闭包(Closure)
    Swift的Guard语句
    Swift 学习指引
    Swift 4.0 废弃的柯里化
  • 原文地址:https://www.cnblogs.com/lychnis/p/11743120.html
Copyright © 2011-2022 走看看