File tree Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Expand file tree Collapse file tree 1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/decode-ways/
2
+
3
+ class Solution :
4
+ def numDecodings1 (self , s : str ) -> int :
5
+ """
6
+ [Complexity]
7
+ - TC: O(n)
8
+ - SC: O(n)
9
+
10
+ [Approach]
11
+ DP๋ก ํ ์ ์๋ค.
12
+ dp[i] = s[i]๊น์ง ๋ดค์ ๋, ๊ฐ๋ฅํ decoding ๊ฐ์์ ์ดํฉ
13
+ 1) s[i]ย ํ ์๋ฆฌ๋ง ๊ฐ๋ฅํ ๊ฒฝ์ฐ: s[i] != 0
14
+ => dp[i] += dp[i - 1]
15
+ 2) s[i - 1:i + 1] ๋ ์๋ฆฌ ๋ชจ๋ ๊ฐ๋ฅํ ๊ฒฝ์ฐ: 10 <= s[i - 1:i + 1] <= 26
16
+ => dp[i] += dp[i - 2]
17
+ ๋ฐ๋ผ์, ์ด๊ธฐ ๊ฐ์ผ๋ก dp[0], dp[1]์ ๋จผ์ ์ฑ์์ฃผ์ด์ผ ํ๋ค.
18
+ """
19
+
20
+ n = len (s )
21
+ dp = [0 ] * n
22
+
23
+ # early stop
24
+ if s [0 ] == "0" :
25
+ return 0
26
+ if n == 1 :
27
+ return 1
28
+
29
+ # initialize (dp[0], dp[1])
30
+ dp [0 ] = 1
31
+ if s [1 ] != "0" :
32
+ dp [1 ] += dp [0 ]
33
+ if 10 <= int (s [0 :2 ]) <= 26 :
34
+ dp [1 ] += 1
35
+
36
+ # iterate (dp[2] ~)
37
+ for i in range (2 , n ):
38
+ # 1) s[i]ย ํ ์๋ฆฌ๋ง ๊ฐ๋ฅํ ๊ฒฝ์ฐ
39
+ if s [i ] != "0" :
40
+ dp [i ] += dp [i - 1 ]
41
+ # 2) s[i - 1:i + 1] ๋ ์๋ฆฌ ๋ชจ๋ ๊ฐ๋ฅํ ๊ฒฝ์ฐ
42
+ if 10 <= int (s [i - 1 :i + 1 ]) <= 26 :
43
+ dp [i ] += dp [i - 2 ]
44
+
45
+ return dp [- 1 ]
46
+
47
+ def numDecodings (self , s : str ) -> int :
48
+ """
49
+ [Complexity]
50
+ - TC: O(n)
51
+ - SC: O(1)
52
+
53
+ [Approach]
54
+ O(n) space DP์์ ๋งค ๋จ๊ณ์์ dp[i - 1], dp[i - 2] ๋ ๊ฐ๋ง ํ์ธํ๋ฏ๋ก, O(1) space๋ก space optimize ํ ์ ์๋ค.
55
+ dp[i - 1] = prev1
56
+ dp[i - 2] = prev2
57
+ """
58
+
59
+ prev2 , prev1 = 1 , 1 if s [0 ] != "0" else 0
60
+
61
+ for i in range (1 , len (s )):
62
+ curr = 0 # = dp[i]
63
+
64
+ # 1) s[i]ย ํ ์๋ฆฌ๋ง ๊ฐ๋ฅํ ๊ฒฝ์ฐ
65
+ if s [i ] != "0" :
66
+ curr += prev1
67
+ # 2) s[i - 1:i + 1] ๋ ์๋ฆฌ ๋ชจ๋ ๊ฐ๋ฅํ ๊ฒฝ์ฐ
68
+ if 10 <= int (s [i - 1 :i + 1 ]) <= 26 :
69
+ curr += prev2
70
+
71
+ prev2 , prev1 = prev1 , curr
72
+
73
+ return prev1
You canโt perform that action at this time.
0 commit comments