File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # Leetcode 91. Decode Ways
3
+
4
+ use **dynamic programming** to solve this problem.
5
+
6
+ ## Time and Space Complexity
7
+
8
+ ```
9
+ TC: O(n)
10
+ SC: O(n)
11
+ ```
12
+
13
+ ### TC is O(n):
14
+ - iterating through the string and checking if the current character is decodable. = O(n)
15
+
16
+ ### SC is O(n):
17
+ - creating a dp array of size n + 1 = O(n)
18
+ '''
19
+ class Solution :
20
+ def isDecodable (self , str : str ):
21
+ return 1 <= int (str ) <= 26 and str [0 ] != '0'
22
+
23
+ def numDecodings (self , s : str ) -> int :
24
+ if s [0 ] == "0" :
25
+ return 0
26
+
27
+ n = len (s )
28
+ dp = (n + 1 ) * [0 ]
29
+ dp [0 ] = 1
30
+ dp [1 ] = 1
31
+
32
+ for i in range (2 , n + 1 ):
33
+ one = s [i - 1 ]
34
+ two = s [i - 2 :i ]
35
+
36
+ if self .isDecodable (one ):
37
+ dp [i ] += dp [i - 1 ]
38
+ if self .isDecodable (two ):
39
+ dp [i ] += dp [i - 2 ]
40
+
41
+ return dp [n ]
42
+
43
+ '''
44
+ # sudo code
45
+ - ํฌํผํจ์: 0์ผ๋ก ์์ํ์ง ์๊ณ , 1~26์ธ ๊ฒฝ์ฐ True
46
+ - numDecodingsํจ์
47
+ 1. n: ๋ฌธ์์ด s์ ๊ธธ์ด
48
+ 2. dp: ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ๋ฐฐ์ด, n+1
49
+ 3. BaseCase: dp[0] = 1, dp[1] = 1
50
+ 4. for loop 2 to n:
51
+ one = s์ i-1 ์์น์ 1๊ธ์ (ํ์ฌ ๊ธ์)
52
+ two = s์ i-2๋ถํฐ i๊น์ง ์๋ฅธ 2๊ธ์ (ํ์ฌ ๊ธ์ ํฌํจ ์ด์ ๊ธ์)
53
+ if one is decodable => dp[i] += dp[i - 1] i๊ธธ์ด์ผ ๋, dp์ -1 ๊ฒฝ์ฐ์ ๋งํผ์ ์ถ๊ฐ (ํ์ฌ ๊ธ์๋ฅผ ํ ๊ธ์๋ก ํด์)
54
+ if two is decodable => dp[i] += dp[i - 2] i๊ธธ์ด์ผ ๋, dp์ -2 ๊ฒฝ์ฐ์ ์ ๋งํผ ์ถ๊ฐ (ํ์ฌ ๊ธ์๋ฅผ ๋ ๊ธ์๋ก ํด์)
55
+ 5. dp[n] ๋ฐํ: ์ต์ข
๋์ฝ๋ ๊ฐ๋ฅํ ๊ฒฝ์ฐ์ ์ ๊ฒฐ๊ณผ
56
+ '''
You canโt perform that action at this time.
0 commit comments