diff --git a/solutions/62. Unique Paths/README.md b/solutions/62. Unique Paths/README.md index 99aa4ce..2b2222d 100644 --- a/solutions/62. Unique Paths/README.md +++ b/solutions/62. Unique Paths/README.md @@ -59,3 +59,13 @@ dp[i][j] = dp[i-1][j] + dp[i][j-1] * 複雜度: * 時間複雜度:O(M * N) * 空間複雜度:O(M * N) + +仔細觀察,會發現不需要用 M * N 的空間,只需要一個一維的陣列,因為每次只需要用到上一個 row 的資料,所以可以省略掉一個維度。這樣空間複雜度就會變成 O(N): + +``` +dp[j] += dp[j - 1] +``` + +* 複雜度: + * 時間複雜度:O(M * N) + * 空間複雜度:O(N) \ No newline at end of file diff --git a/solutions/62. Unique Paths/solution.py b/solutions/62. Unique Paths/solution.py index 027dabe..f69ff05 100644 --- a/solutions/62. Unique Paths/solution.py +++ b/solutions/62. Unique Paths/solution.py @@ -1,10 +1,10 @@ class Solution: def uniquePaths(self, m: int, n: int) -> int: - dp = [[0] * n for _ in range(m)] - for i in range(m): - for j in range(n): - if i == 0 or j == 0: - dp[i][j] = 1 - else: - dp[i][j] = dp[i-1][j] + dp[i][j-1] - return dp[-1][-1] + dp = [1] * n + + for _ in range(1, m): + for j in range(1, n): + dp[j] += dp[j - 1] + + return dp[-1] + \ No newline at end of file