[Leetcode] 64. Minimum Path Sum 解题报告
来源:互联网 发布:该死的妹子软件 编辑:程序博客网 时间:2024/05/21 16:48
题目:
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.
思路:
还是典型的动态规划问题。定义dp[r][c]表示到达第r - 1行第c - 1列的时候的路径最小和,则递推公式为:dp[r][c] = min(dp[r - 1][c], dp[r][c - 1]) + grid[r - 1][c - 1]。考虑到dp仍然只和与它最近的两个元素有递推关系,所以空间复杂度仍然可以优化到O(min(m, n)),其中m和n分别表示grid的行个数和列个数。为了简便,下面的代码仅仅将空间复杂度优化到O(n),但是做到这一点就足以通过面试官的bar了,进一步提出优化到O(min(m, n))也许会有额外加分。
代码:
class Solution {public: int minPathSum(vector<vector<int>>& grid) { int row = grid.size(); if (row == 0) { return 0; } int col = grid[0].size(); if (col == 0) { return 0; } vector<int> dp(col + 1, INT_MAX); dp[1] = 0; for (int r = 1; r <= row; ++r) { for (int c = 1; c <= col; ++c) { dp[c] = min(dp[c - 1], dp[c]) + grid[r - 1][c - 1]; } } return dp[col]; }};
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]Minimum Path Sum,解题报告
- 【LeetCode】Minimum Path Sum 解题报告
- [LeetCode] Minimum Path Sum 解题报告
- Leetcode 64. Minimum Path Sum 最小路径和 解题报告
- [LeetCode]Path Sum,解题报告
- 【LeetCode】Path Sum 解题报告
- Leetcode解题笔记 64. Minimum Path Sum [Medium] 动态规划
- leetcode解题方案--064--Minimum Path Sum
- LeetCode-Minimum Size Subarray Sum-解题报告
- [LeetCode]64.Minimum Path Sum
- LeetCode --- 64. Minimum Path Sum
- LeetCode 64.Minimum Path Sum
- [Leetcode] 64. Minimum Path Sum
- 【Nginx】nginx配置openssl 证书,https
- 做一个不死的人
- 最基本的javaweb项目环境的搭建
- ./configure && make && make install 编译安装和卸载 (Linux)
- Unity 3d 文章迁移
- [Leetcode] 64. Minimum Path Sum 解题报告
- /proc目录
- 类与对象
- java同步方法和同步代码块
- 二级联动 国省市选择
- 小人脸检测 - Finding Tiny Faces
- 2017版高校邦-计算思维 完整答案
- hadoop 序列化和排序,自定义分区
- php知识