Skip to content

Commit

Permalink
feat: [Week 02-5] solve decode-ways
Browse files Browse the repository at this point in the history
  • Loading branch information
Chaedie committed Dec 17, 2024
1 parent 4ddb7c6 commit d12889a
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions decode-ways/Chaedie.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"""
dp λ¬Έμ œλŠ” 아직 μ–΄μƒ‰ν•΄μ„œ 직접 풀진 λͺ»ν–ˆμŠ΅λ‹ˆλ‹€.
"""

"""
μž¬κ·€μ™€ dp hash_map 을 ν™œμš©ν•œ 캐싱 μ „λž΅
Time: O(n)
Space: O(n) = O(n) + O(n)
"""


class Solution:
def numDecodings(self, s: str) -> int:
dp = {len(s): 1}

def dfs(i):
if i in dp:
return dp[i]
if s[i] == "0":
return 0

# ν•œμžλ¦¬ 숫자
res = dfs(i + 1)

# λ‘μžλ¦¬ 숫자
if i + 1 < len(s) and (
s[i] == "1" or s[i] == "2" and s[i + 1] in "0123456"
):
res += dfs(i + 2)
dp[i] = res
return res

return dfs(0)


"""
iterative dp
Time: O(n)
Space: O(n)
"""


class Solution:
def numDecodings(self, s: str) -> int:
dp = {len(s): 1}

for i in range(len(s) - 1, -1, -1):
if s[i] == "0":
dp[i] = 0
else:
dp[i] = dp[i + 1]

if i + 1 < len(s) and (
s[i] == "1" or s[i] == "2" and s[i + 1] in "0123456"
):
dp[i] += dp[i + 2]
return dp[0]

0 comments on commit d12889a

Please sign in to comment.