File tree Expand file tree Collapse file tree 1 file changed +26
-21
lines changed
Expand file tree Collapse file tree 1 file changed +26
-21
lines changed Original file line number Diff line number Diff line change 11class Solution :
22 def numDecodings (self , s : str ) -> int :
3- if s [0 ] == '0' :
4- return 0
3+ memo = {}
4+
5+ def decode (index ):
6+ # ์ด๋ฏธ ๊ณ์ฐํ์ผ๋ฉด ๋ฐ๋ก ๋ฐํ
7+ if index in memo :
8+ return memo [index ]
9+
10+ # ๊ธฐ์ ์ฌ๋ก
11+ ## ๋๊น์ง ์์ผ๋ฉด ์ฑ๊ณต
12+ if index == len (s ):
13+ return 1
14+ ## 0์ผ๋ก ์์ํ๋ฉด ๋ถ๊ฐ๋ฅ
15+ if s [index ] == '0' :
16+ return 0
17+
18+ # ์ฌ๊ท ๊ณ์ฐ
19+ ways = decode (index + 1 )
20+
21+ if index + 1 < len (s ) and int (s [index :index + 2 ]) <= 26 :
22+ ways += decode (index + 2 )
23+
24+ # ๋ฉ๋ชจ์ด์ ์ด์
25+ memo [index ] = ways
26+ return ways
527
6- n = len (s )
7- # dp[i]๋ฅผ i๋ฒ์จฐ๊น์ง ์ฒ๋ฆฌํ์๋์ ๊ฒฝ์ฐ์ ์์ ํฉ์ผ๋ก ์ ์
8- dp = [0 ] * n
9- # dp[0] = 1 (์ฒซ์๋ฆฌ ์)
10- dp [0 ] = 1
11-
12- # i๋ฒ์จฐ ์ซ์๊ฐ 1~9๋ก ๋์ฒด๋ ์ ์์ผ๋ฉด ์ด์ ๊น์ง์ ๊ฒฝ์ฐ์ ์ ํฉ์ ์ด์ด๊ฐ
13- # i๋ฒ์จฐ ์ซ์(๋์๋ฆฌ์)๊ฐ 10~26์ผ๋ก ๋์ฒด๋ ์ ์์ผ๋ฉด ์์๋ฆฌ๋ ์ฌ์ฉํ ๊ฒ์ด๋ฏ๋ก ๊ทธ ์์๋ฆฌ๊น์ง์ ์ํ๋ฅผ ๊ฐ์ ธ์ด
1428 # ์๊ฐ๋ณต์ก๋, ๊ณต๊ฐ๋ณต์ก๋ O(n)
15- for i in range (1 , n ):
16- num1 = int (s [i ])
17- num2 = int (s [i - 1 : i + 1 ])
18- if 1 <= num1 <= 9 :
19- dp [i ] += dp [i - 1 ]
20- if 10 <= num2 <= 26 :
21- if i == 1 :
22- dp [i ] += 1
23- else :
24- dp [i ] += dp [i - 2 ]
25- return dp [n - 1 ]
29+
30+ return decode (0 )
You canโt perform that action at this time.
0 commit comments