File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change 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 ]
You canโt perform that action at this time.
0 commit comments