[leetcode] 64. Minimum Path Sum
来源:互联网 发布:java 迭代器模式 编辑:程序博客网 时间:2024/06/18 00:39
Question:
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 1:
[[1,3,1] [1,5,1] [4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
Solution:
用动态规划,思路和做过的174. Dungeon Game是一样的,而且没那题那么复杂要考虑几种情况。
从最右下方开始往回遍历,状态转移方程为:
f(i, j) = min(f(i, j+1), f(i+1, j)) + nums(i, j)
即每次只可以去右边或者下边,选最小的那个走就行了。初始化时f(m, n) = nums(m, n)
并且注意边界的情况就好。
和174那题一样,空间上可以只用一维数组,可以用f(j+1)
代替 f(i, j+1)
因为f(j+1)
是最新更新的,用f(j)
代替f(i+1, j)
因为f(j)
是之前 (i-1)
那一层的。
class Solution {public: int minPathSum(vector<vector<int>>& grid) { if (grid.size() == 0) return 0; int m = grid.size(), n = grid[0].size(); vector<int> dp(n, 0); dp[n-1] = grid[m-1][n-1]; for (int j = n-2; j >= 0; j--) dp[j] = dp[j+1] + grid[m-1][j]; for (int i = m-2; i >= 0; i--) { dp[n-1] += grid[i][n-1]; for (int j = n-2; j >= 0; j--) { dp[j] = min(dp[j+1], dp[j]) + grid[i][j]; } } return dp[0]; }};
阅读全文
0 0
- [LeetCode]64.Minimum Path Sum
- LeetCode --- 64. Minimum Path Sum
- LeetCode 64.Minimum Path Sum
- [Leetcode] 64. Minimum Path Sum
- [leetcode] 64.Minimum Path Sum
- [leetcode] 64.Minimum Path Sum
- LeetCode 64. Minimum Path Sum
- 64. Minimum Path Sum LeetCode
- [LeetCode]64. Minimum Path Sum
- leetcode 64. Minimum Path Sum
- [leetcode] 64. Minimum Path Sum
- LeetCode 64. Minimum Path Sum
- LeetCode *** 64. Minimum Path Sum
- leetcode 64. Minimum Path Sum
- 【leetcode】64. Minimum Path Sum
- Leetcode:64. Minimum Path Sum
- LeetCode-64.Minimum Path Sum
- LeetCode 64. Minimum Path Sum
- 对象流的读入与写出
- STL-vector
- java--拷贝
- Python自学之路第七步——字典
- Paxos算法与Zookeeper分析
- [leetcode] 64. Minimum Path Sum
- HTML中属性ID和属性NAME有何区别?
- 学习智慧医疗appday02--登录页面的学习
- jvm探秘十:虚拟机字节码执行引擎之栈帧
- POJ 刷题系列:2262. Goldbach's Conjecture
- 网络判断
- 静态html利用ajax实现微信jssdk分享
- html学习 -2
- 类型及数值类型转换