64. Minimum Path Sum
Posted lychnis
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]; } };
以上是关于64. Minimum Path Sum的主要内容,如果未能解决你的问题,请参考以下文章