forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdusunax.py
56 lines (45 loc) ยท 1.54 KB
/
dusunax.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
'''
# Leetcode 91. Decode Ways
use **dynamic programming** to solve this problem.
## Time and Space Complexity
```
TC: O(n)
SC: O(n)
```
### TC is O(n):
- iterating through the string and checking if the current character is decodable. = O(n)
### SC is O(n):
- creating a dp array of size n + 1 = O(n)
'''
class Solution:
def isDecodable(self, str: str):
return 1 <= int(str) <= 26 and str[0] != '0'
def numDecodings(self, s: str) -> int:
if s[0] == "0":
return 0
n = len(s)
dp = (n + 1) * [0]
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
one = s[i - 1]
two = s[i - 2:i]
if self.isDecodable(one):
dp[i] += dp[i - 1]
if self.isDecodable(two):
dp[i] += dp[i - 2]
return dp[n]
'''
# sudo code
- ํฌํผํจ์: 0์ผ๋ก ์์ํ์ง ์๊ณ , 1~26์ธ ๊ฒฝ์ฐ True
- numDecodingsํจ์
1. n: ๋ฌธ์์ด s์ ๊ธธ์ด
2. dp: ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ๋ฐฐ์ด, n+1
3. BaseCase: dp[0] = 1, dp[1] = 1
4. for loop 2 to n:
one = s์ i-1 ์์น์ 1๊ธ์ (ํ์ฌ ๊ธ์)
two = s์ i-2๋ถํฐ i๊น์ง ์๋ฅธ 2๊ธ์ (ํ์ฌ ๊ธ์ ํฌํจ ์ด์ ๊ธ์)
if one is decodable => dp[i] += dp[i - 1] i๊ธธ์ด์ผ ๋, dp์ -1 ๊ฒฝ์ฐ์ ๋งํผ์ ์ถ๊ฐ (ํ์ฌ ๊ธ์๋ฅผ ํ ๊ธ์๋ก ํด์)
if two is decodable => dp[i] += dp[i - 2] i๊ธธ์ด์ผ ๋, dp์ -2 ๊ฒฝ์ฐ์ ์ ๋งํผ ์ถ๊ฐ (ํ์ฌ ๊ธ์๋ฅผ ๋ ๊ธ์๋ก ํด์)
5. dp[n] ๋ฐํ: ์ต์ข
๋์ฝ๋ ๊ฐ๋ฅํ ๊ฒฝ์ฐ์ ์ ๊ฒฐ๊ณผ
'''