File tree 1 file changed +43
-9
lines changed
1 file changed +43
-9
lines changed Original file line number Diff line number Diff line change 2
2
Constraints:
3
3
- 1 <= m, n <= 100
4
4
5
- <Solution 1>
5
+ <Solution 1: 조합 활용 >
6
6
7
7
Time Complexity: O(1)
8
8
- math.comb() 사용
15
15
1. (m-1)번 아래로, (n-1)번 오른쪽으로 가야함 -> 총 (m+n-2)번 이동
16
16
2. 결국 (m+n-2)번의 이동 중 (n-1)번의 오른쪽 이동을 선택하는 조합의 수
17
17
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
+ - 풀이가 간결함, 하지만 큰 수에서 오버플로우 가능성 있음
21
20
"""
22
21
class Solution :
23
22
def uniquePaths (self , m : int , n : int ) -> int :
24
23
from math import comb
25
24
return comb (m + n - 2 , n - 1 )
26
25
27
26
"""
28
- <Solution 2>
27
+ <Solution 2: DP 활용 >
29
28
30
- Time Complexity:
31
- -
29
+ Time Complexity: O(m * n)
30
+ - m은 row, n은 column의 길이
31
+ - 메모이제이션 활용, 모든 좌표에서 재귀 함수의 호출이 딱 한번만 일어나기 때문
32
32
33
- Space Complexity:
34
- -
33
+ Space Complexity: O(m * n)
34
+ - 함수의 호출 결과를 저장하는데 격자의 넓이에 비례하는 공간이 필요
35
35
36
36
풀이방법:
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. 아래, 오른쪽, 오른쪽
37
53
"""
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
38
71
72
+ return dfs (0 , 0 )
You can’t perform that action at this time.
0 commit comments