Skip to content

Commit b506385

Browse files
committedDec 21, 2024ยท
add solution: decode-ways
ยท
v4.13.0v3.2.0
1 parent c7d7f84 commit b506385

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
 

โ€Ždecode-ways/dusunax.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
'''

0 commit comments

Comments
 (0)
Please sign in to comment.