Skip to content

Commit 49c729d

Browse files
committed
[7th batch] week 3 - decode ways
1 parent d8ba0d1 commit 49c729d

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

โ€Ždecode-ways/liza0525.pyโ€Ž

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# 7๊ธฐ ํ’€์ด
2+
# ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
3+
# - memoization์„ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ ์ธ๋ฑ์Šค ๋ณ„๋กœ ๊ฐ€๋Šฅํ•œ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•  ๋•Œ ํ•œ ๋ฒˆ ์”ฉ๋งŒ ๊ณ„์‚ฐ
4+
# ๊ณต๊ฐ„๋ณต์žก๋„: O(n)
5+
# - ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋งŒํผ memo ๊ฐ’์ด ๋Š˜์–ด๋‚จ
6+
class Solution:
7+
# DP๋ฅผ ์ด์šฉํ•ด ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด ๋œ๋‹ค.
8+
# ๊ฐ ์ธ๋ฑ์Šค๋กœ ๋ณ„๋กœ ๋ฌธ์ž์—ด์„ ์ž˜๋ž์„ ๋•Œ์˜ ๊ฐ€๋Šฅํ•œ ๋””์ฝ”๋”ฉ ๋ฐฉ๋ฒ• ์ˆ˜๋ฅผ memoํ•œ๋‹ค
9+
def numDecodings(self, s: str) -> int:
10+
len_s = len(s)
11+
memo = {}
12+
13+
def dfs(index):
14+
if index == len_s: # ๋๊นŒ์ง€ ํƒ์ƒ‰ํ–ˆ๋‹ค๋ฉด ๊ฐ€๋Šฅํ•œ ๋””์ฝ”๋”ฉ ๋ฐฉ๋ฒ•์ด๋ฏ€๋กœ 1์„ return
15+
return 1
16+
17+
if s[index] == '0': # ํ˜„์žฌ index์˜ ๋ฌธ์ž๊ฐ€ '0'์ด๋ฉด ํ•ด๋‹น ๋ฐฉ๋ฒ•์€ ๋””์ฝ”๋”ฉ์ด ๋ถˆ๊ฐ€ํ•œ ๊ฒƒ์œผ๋กœ ํŒ๋‹จ 0์„ return
18+
return 0
19+
20+
if index in memo: # ์ด๋ฏธ ์ €์žฅ๋˜์–ด ์žˆ๋‹ค๋ฉด memo ๊ฐ’์„ return
21+
return memo[index]
22+
23+
result = dfs(index + 1) # index๋กœ๋ถ€ํ„ฐ ํ•œ ์ž๋ฆฌ ์ˆ˜๋งŒ ๊ณ„์‚ฐํ•  ๋•Œ, ๋‹ค์Œ ๊ณ„์‚ฐ์€ index + 1์ด ๋œ๋‹ค
24+
25+
if (
26+
index + 1 < len_s
27+
and int(s[index:index + 2]) <= 26
28+
): # index~index+1์˜ ๋ฌธ์ž์—ด์ด 26๋ณด๋‹ค ์ž‘์€ ๋‘ ์ž๋ฆฌ ์ˆ˜์ผ ๋•Œ๋งŒ index + 2๋ฒˆ์งธ ๊ณ„์‚ฐ์„ ํ•œ๋‹ค
29+
result += dfs(index + 2)
30+
31+
memo[index] = result # memoization์„ ํ•œ๋‹ค
32+
return result
33+
34+
return dfs(0)

0 commit comments

Comments
ย (0)