Skip to content

Commit b0c09b9

Browse files
committed
solve(w07): 62. Unique Paths
1 parent 021c27e commit b0c09b9

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

unique-paths/seungriyou.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# https://leetcode.com/problems/unique-paths/
2+
3+
class Solution:
4+
def uniquePaths_2d(self, m: int, n: int) -> int:
5+
"""
6+
[Complexity]
7+
- TC: O(m * n)
8+
- SC: O(m * n)
9+
10+
[Approach]
11+
로봇이 down or right로만 이동할 수 있으므로, 어떤 칸에 도달할 수 있는 unique path의 개수는 up 칸과 left 칸까지의 unique path의 개수를 더한 값이 된다.
12+
따라서 2D DP로 풀 수 있으며, dp table은 다음과 같다.
13+
dp[r][c] = (up 칸까지의 unique path) + (left 칸까지의 unique path)
14+
= dp[r - 1][c] + dp[r][c - 1]
15+
이때, dp table의 첫 번째 row와 column에 있는 칸들은 모두 도달할 수 있는 unique path의 개수가 1이므로 초기화해준다.
16+
"""
17+
dp = [[0 for _ in range(n)] for _ in range(m)]
18+
19+
# 첫 번째 row & column 초기화
20+
for r in range(m):
21+
dp[r][0] = 1
22+
for c in range(n):
23+
dp[0][c] = 1
24+
25+
for r in range(1, m):
26+
for c in range(1, n):
27+
dp[r][c] = dp[r - 1][c] + dp[r][c - 1]
28+
29+
return dp[m - 1][n - 1]
30+
31+
def uniquePaths(self, m: int, n: int) -> int:
32+
"""
33+
[Complexity]
34+
- TC: O(m * n)
35+
- SC: O(n) (1D DP로 space optimization)
36+
37+
[Approach]
38+
2D DP에서 dp[r][c]를 구할 때 dp[r - 1][c]과 dp[r][c - 1]만 사용하므로,
39+
rolling array 기법을 이용해 1D DP로 space optimization이 가능하다.
40+
따라서 길이가 n인 1D dp list를 이용해
41+
- c(= 1 ~ n - 1)를 순회하며 dp[c] += dp[c - 1]로 업데이트하는 것을 (2D DP에서의 dp[r - 1][c]가 dp[c] 값이므로!)
42+
- row 개수인 m 번 반복
43+
하면 된다.
44+
"""
45+
46+
dp = [0] * n
47+
dp[0] = 1
48+
49+
for _ in range(m):
50+
for c in range(1, n):
51+
dp[c] += dp[c - 1]
52+
53+
return dp[n - 1]

0 commit comments

Comments
 (0)