forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhaklee.py
32 lines (26 loc) Β· 1.18 KB
/
haklee.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
"""TC: O(n), SC: O(1)
μμ΄λμ΄:
λ· kκ°μ κΈμλ₯Ό λμ½λ© νλ κ²½μ°μ μλ₯Ό f(k)λΌκ³ νμ.
f(k)λ λ€μμ λ κ²½μ°μ μλ₯Ό λν κ°μ΄λ€.
- λ· kκ°μ κΈμ μ€ μ²« κΈμκ° λμ½λ© κ°λ₯ν κ²½μ°, λ· k-1κΈμλ₯Ό λμ½λ©νλ κ²½μ°μ μ
- λ· kκ°μ κΈμ μ€ μ λ κΈμκ° λμ½λ© κ°λ₯ν κ²½μ°, λ· k-2κΈμλ₯Ό λμ½λ©νλ κ²½μ°μ μ
μ¦, f(k) = (μ λ κΈμ νλ³)*f(k-2) + (μ ν κΈμ νλ³)*f(k-1)
SC:
- tabulation κ³Όμ μμ κ° 2κ°λ§ κ³μ μ μ§νλ€.
- μ¦, O(1).
TC:
- f(k) ꡬνλ μ: O(1)
- λ κΈμκ° λμ½λ© κ°λ₯νμ§ νλ³: O(1)
- 첫 κΈμκ° λμ½λ© κ°λ₯νμ§ νλ³: O(1)
- μμ f(k)λ₯Ό ꡬνλ κ²μ sμ κΈΈμ΄μμ 2λ₯Ό λΊ μλ§νΌ 루ν, μ¦, O(n)
- μ’
ν©νλ©΄ O(n).
"""
class Solution:
def numDecodings(self, s: str) -> int:
# init
x, y = 1, int(int(s[-1]) != 0) # f(0), f(1)
# tabulation
for i in range(len(s) - 2, -1, -1): # λ· kκ° κΈμμ μμ κΈμκ° s[i]
# f(k-2), f(k-1)μ f(k-1), f(k)λ‘
x, y = y, (x * (10 <= int(s[i : i + 2]) <= 26)) + (y * (int(s[i]) != 0))
return y