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