From 6a4eba94df4e24e3f3284d55399290c23e13ee57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= Date: Mon, 18 Feb 2019 23:28:44 +0800 Subject: [PATCH] Update 63. Unique Paths II.md --- solutions/63. Unique Paths II.md | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/solutions/63. Unique Paths II.md b/solutions/63. Unique Paths II.md index e293f53..bb9f53a 100644 --- a/solutions/63. Unique Paths II.md +++ b/solutions/63. Unique Paths II.md @@ -2,7 +2,9 @@ # 思路 这题其实和[62. Unique Paths](https://leetcode.com/problems/unique-paths/)几乎一样的,唯一区别就是矩形网格里存在一些障碍物,我们对每个格子判断一下就行了。 就是一个简单的动归,可参考[62题题解](https://github.com/ShusenTang/LeetCode/blob/master/solutions/62.%20Unique%20Paths.md)。 -时间空间复杂度都是O(mn) +时间空间复杂度都是O(mn) +另外,类似62题,可将空间复杂度优化到O(m),这里不再赘述,可参考[讨论区](https://leetcode.com/problems/unique-paths-ii/discuss/23252/4ms-O(n)-DP-Solution-in-C%2B%2B-with-Explanations) +注意: dp数组开成int型时有的case过不了(之前是没有这些case的,直接int就能过),所以开成long long型的 # C++ ``` C++ @@ -10,14 +12,13 @@ class Solution { public: int uniquePathsWithObstacles(vector>& obstacleGrid) { int m = obstacleGrid.size(), n = obstacleGrid[0].size(); - vector>dp(m + 1, vector(n + 1, 0)); - dp[1][1] = 1; - for(int i = 1; i <= m; i++) - for(int j = 1; j <= n; j++){ - if(obstacleGrid[i - 1][j - 1]) dp[i][j] = 0; // 此处为障碍物 - else dp[i][j] += (dp[i - 1][j] + dp[i][j - 1]); - } - return dp[m][n]; - } + vector > dp(m + 1, vector (n + 1, 0)); + dp[0][1] = 1; + for (int i = 1; i <= m; i++) + for (int j = 1; j <= n; j++) + if (!obstacleGrid[i - 1][j - 1]) + dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; + return int(dp[m][n]); + } }; ```