File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """
2+ # Intuition
3+ dp[n]μ sμ nλ²μ§Έ κΈμκΉμ§ λμ½λ©ν μ μλ κ²½μ°μ μ
4+ dp[n] = dp[n-1](if can be decoded) + dp[n-2](if can be decoded)
5+
6+ # Approach
7+ i-1 ~ iκΉμ§μ μ«μ, i-2 ~ iκΉμ§μ μ«μκ° κ°κ° λμ½λ© λ μ μλμ§ νμΈνλ€.
8+ λμ½λ© κ°λ₯νλ©΄ κ·Έ μμΉμ dp λ°°μ΄μ κ°μ κ°κ° λνκ³ , λμ½λ© λΆκ°λ₯νλ©΄ λνμ§ μλλ€.
9+
10+ # Complexity
11+ - Time complexity: Nμ sμ κΈΈμ΄λΌκ³ ν λ, λ°λ³΅λ¬ΈμΌλ‘ O(N)
12+
13+ - Space complexity: dp λ°°μ΄ λ§λλ λ°μ O(N)
14+ """
15+
16+
17+ class Solution :
18+ def numDecodings (self , s : str ) -> int :
19+ n = len (s )
20+ dp = [0 ] * (n + 1 )
21+ dp [1 ] = 1 if s [0 ] != "0" else 0
22+ if dp [1 ] == 0 or n == 1 :
23+ return dp [1 ]
24+ dp [2 ] = 1 if int (s [1 ]) > 0 else 0
25+ dp [2 ] += 1 if int (s [:2 ]) > 9 and int (s [:2 ]) < 27 else 0
26+ for i in range (3 , n + 1 ):
27+ dp [i ] = dp [i - 1 ] if s [i - 1 : i ] != "0" else 0
28+ dp [i ] += dp [i - 2 ] if s [i - 2 : i ] > "09" and s [i - 2 : i ] < "27" else 0
29+ return dp [n ]
You canβt perform that action at this time.
0 commit comments