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)