Skip to content

Commit 8cb65c8

Browse files
committed
feat: Solve decode-ways problem
1 parent 1c32cb4 commit 8cb65c8

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

โ€Ždecode-ways/hu6r1s.py

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
class Solution:
2+
def numDecodings(self, s: str) -> int:
3+
"""
4+
1. ์žฌ๊ท€ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์‚ฌ์šฉ
5+
_
6+
226 -> B, 26
7+
_
8+
26 -> B, 6
9+
_
10+
6 -> F "BBF"
11+
__
12+
26 -> Z "BZ"
13+
__
14+
226 -> V, 6
15+
_
16+
6 -> F "VF"
17+
18+
์‹œ๊ฐ„๋ณต์žก๋„: O(2^n) - ์ค‘๋ณต ๊ณ„์‚ฐ์ด ๋งŽ์•„ ๋งค์šฐ ๋น„ํšจ์œจ์ 
19+
๊ณต๊ฐ„๋ณต์žก๋„: O(n) - ์ตœ๋Œ€ ์žฌ๊ท€ ๊นŠ์ด๋งŒํผ ์Šคํƒ ์‚ฌ์šฉ
20+
"""
21+
# def dfs(start):
22+
# if start == len(s):
23+
# return 1
24+
# if s[start] == "0":
25+
# return 0
26+
# if start + 1 < len(s) and int(s[start:start+2]) < 27:
27+
# return dfs(start+1) + dfs(start+2)
28+
# else:
29+
# return dfs(start+1)
30+
# return dfs(0)
31+
32+
"""
33+
2. ์žฌ๊ท€ + ๋ฉ”๋ชจ๋ฆฌ์ œ์ด์…˜
34+
์‹œ๊ฐ„๋ณต์žก๋„: O(n) - ๊ฐ ์‹œ์ž‘ ์œ„์น˜์— ๋Œ€ํ•ด ํ•œ ๋ฒˆ๋งŒ ๊ณ„์‚ฐ
35+
๊ณต๊ฐ„๋ณต์žก๋„: O(n) - ๋ฉ”๋ชจ์ด์ œ์ด์…˜ ๋”•์…”๋„ˆ๋ฆฌ์™€ ์žฌ๊ท€ ์Šคํƒ
36+
"""
37+
# memo = {len(s): 1}
38+
# def dfs(start):
39+
# if start in memo:
40+
# return memo[start]
41+
# if s[start] == "0":
42+
# memo[start] = 0
43+
# elif start + 1 < len(s) and int(s[start:start+2]) < 27:
44+
# memo[start] = dfs(start+1) + dfs(start+2)
45+
# else:
46+
# memo[start] = dfs(start+1)
47+
48+
# return memo[start]
49+
# return dfs(0)
50+
51+
"""
52+
3. DP
53+
์‹œ๊ฐ„๋ณต์žก๋„ (Time Complexity): O(n)
54+
- ๋ฌธ์ž์—ด s์˜ ๊ธธ์ด๋งŒํผ ํ•œ ๋ฒˆ์˜ ๋ฃจํ”„๋ฅผ ๋„๋Š” DP ๋ฐฉ์‹
55+
56+
๊ณต๊ฐ„๋ณต์žก๋„ (Space Complexity): O(n)
57+
- ๊ธธ์ด n+1์งœ๋ฆฌ dp ๋ฐฐ์—ด ์‚ฌ์šฉ
58+
- ๊ณต๊ฐ„ ์ตœ์ ํ™”๋ฅผ ํ•˜๋ฉด O(1)๋กœ ์ค„์ผ ์ˆ˜ ์žˆ์Œ
59+
"""
60+
dp = [0] * len(s) + [1]
61+
for i in range(len(s)-1, -1, -1):
62+
if s[i] == "0":
63+
dp[i] = 0
64+
elif i + 1 < len(s) and int(s[i:i+2]) < 27:
65+
dp[i] = dp[i+1] + dp[i+2]
66+
else:
67+
dp[i] = dp[i+1]
68+
return dp[0]

0 commit comments

Comments
ย (0)