码迷,mamicode.com
首页 > 其他好文 > 详细

64. Minimum Path Sum

时间:2019-10-26 14:57:10      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:ini   结果   css   empty   exp   练手   path   ons   ast   

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];
    }
};

 

64. Minimum Path Sum

标签:ini   结果   css   empty   exp   练手   path   ons   ast   

原文地址:https://www.cnblogs.com/lychnis/p/11743120.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!