Skip to content

Commit 477b529

Browse files
committed
Add the second solution for Unique paths
1 parent de12e5b commit 477b529

File tree

1 file changed

+43
-9
lines changed

1 file changed

+43
-9
lines changed

unique-paths/KwonNayeon.py

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Constraints:
33
- 1 <= m, n <= 100
44
5-
<Solution 1>
5+
<Solution 1: 조합 활용>
66
77
Time Complexity: O(1)
88
- math.comb() 사용
@@ -15,24 +15,58 @@
1515
1. (m-1)번 아래로, (n-1)번 오른쪽으로 가야함 -> 총 (m+n-2)번 이동
1616
2. 결국 (m+n-2)번의 이동 중 (n-1)번의 오른쪽 이동을 선택하는 조합의 수
1717
3. Combination 공식 적용: (m+n-2)C(n-1)
18-
19-
Further Consideration:
20-
- DP로 풀어보기
18+
- C(m+n-2, n-1) = (m+n-2)! / ((n-1)! × (m-1)!)
19+
- 풀이가 간결함, 하지만 큰 수에서 오버플로우 가능성 있음
2120
"""
2221
class Solution:
2322
def uniquePaths(self, m: int, n: int) -> int:
2423
from math import comb
2524
return comb(m+n-2, n-1)
2625

2726
"""
28-
<Solution 2>
27+
<Solution 2: DP 활용>
2928
30-
Time Complexity:
31-
-
29+
Time Complexity: O(m * n)
30+
- m은 row, n은 column의 길이
31+
- 메모이제이션 활용, 모든 좌표에서 재귀 함수의 호출이 딱 한번만 일어나기 때문
3232
33-
Space Complexity:
34-
-
33+
Space Complexity: O(m * n)
34+
- 함수의 호출 결과를 저장하는데 격자의 넓이에 비례하는 공간이 필요
3535
3636
풀이방법:
37+
- 구현이 복잡함, 하지만 큰 수에서도 안정적임
38+
- 재귀와 메모이제이션을 활용한 Top-down DP 접근법
39+
- 현재 위치에서 목적지까지의 경로 수 = 아래로 이동 + 오른쪽으로 이동
40+
41+
2x3 그리드 예시:
42+
각 위치에서 목적지까지 가는 경로 수:
43+
(0,0)=3 (0,1)=2 (0,2)=1
44+
(1,0)=1 (1,1)=1 (1,2)=1
45+
46+
위치 (0,0)에서 시작:
47+
dfs(0,0) = dfs(1,0) + dfs(0,1) = 1 + 2 = 3
48+
49+
경로 3개:
50+
1. 오른쪽, 오른쪽, 아래
51+
2. 오른쪽, 아래, 오른쪽
52+
3. 아래, 오른쪽, 오른쪽
3753
"""
54+
from functools import cache
55+
class Solution:
56+
def uniquePaths(self, m: int, n: int) -> int:
57+
@cache
58+
def dfs(row, col):
59+
if row == m - 1 and col == n - 1:
60+
return 1
61+
62+
total = 0
63+
64+
if row + 1 < m:
65+
total += dfs(row + 1, col)
66+
67+
if col + 1 < n:
68+
total += dfs(row, col + 1)
69+
70+
return total
3871

72+
return dfs(0, 0)

0 commit comments

Comments
 (0)