From 5fc3a4e7458fc415807b64a450fb24744c671ff5 Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Mon, 10 Feb 2020 20:40:32 +0800 Subject: [PATCH] add 64 --- README.md | 1 + solutions/64. Minimum Path Sum.md | 57 +++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 solutions/64. Minimum Path Sum.md diff --git a/README.md b/README.md index f30b21d..1a50104 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 61 |[Rotate List](https://leetcode.com/problems/rotate-list/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/61.%20Rotate%20List.md)|Medium| | | 62 |[Unique Paths](https://leetcode.com/problems/unique-paths/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/62.%20Unique%20Paths.md)|Medium| | | 63 |[Unique Paths II](https://leetcode.com/problems/unique-paths-ii/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/63.%20Unique%20Paths%20II.md)|Medium| | +| 64 |[Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/)|[C++](solutions/64.%20Minimum%20Path%20Sum.md)|Medium| | | 65 |[Valid Number](https://leetcode.com/problems/valid-number/)|[C++](solutions/65.%20Valid%20Number.md)|Hard| | | 66 |[Plus One](https://leetcode.com/problems/plus-one)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/66.%20Plus%20One.md)|Easy| | | 67 |[Add Binary](https://leetcode.com/problems/add-binary)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/67.%20Add%20Binary.md)|Easy| | diff --git a/solutions/64. Minimum Path Sum.md b/solutions/64. Minimum Path Sum.md new file mode 100644 index 0000000..c9df0d2 --- /dev/null +++ b/solutions/64. Minimum Path Sum.md @@ -0,0 +1,57 @@ +# [64. Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum/) + +# 思路 + +给定一个`m x n`的矩阵,从左上角走到右下角,求最小路径和。就是一个简单的动态规划: +``` +dp[i][j] 代表从 grid[0][0] 走到 grid[i][j] 的最小路径和。 +``` +因为只能往下或者往右走,所以状态更新方程为 +``` +dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]); +``` + +可以利用滚动数组的方式将空间复杂度优化到O(n)或者O(m)。 + + +值得一提的是如果给定的矩阵grid可写的话我们可以就将其作为dp数组,这样就不用额外的空间了。 + +# C++ + +``` C++ +class Solution { +public: + int minPathSum(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + + vector>dp(m, vector(n, INT_MAX)); + dp[0][0] = grid[0][0]; + for(int i = 1; i < m; i++) dp[i][0] = dp[i-1][0] + grid[i][0]; + for(int j = 1; j < n; j++) dp[0][j] = dp[0][j-1] + grid[0][j]; + + for(int i = 1; i < m; i++) + for(int j = 1; j < n; j++) + dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]); + + return dp[m-1][n-1]; + } +}; +``` + +## 滚动数组空间优化 +``` C++ +class Solution { +public: + int minPathSum(vector>& grid) { + int m = grid.size(), n = grid[0].size(); + + vectordp(n, INT_MAX); + dp[0] = 0; + for(int i = 0; i < m; i++) + for(int j = 0; j < n; j++) + dp[j] = grid[i][j] + min(j > 0 ? dp[j-1] : INT_MAX, dp[j]); + + return dp.back(); + } +}; +``` \ No newline at end of file