91. Decode Ways
A message containing letters fromA-Z
is being encoded to numbers using the following mapping:
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message"12"
, it could be decoded as"AB"
(1 2) or"L"
(12).
The number of ways decoding"12"
is 2.
Thoughts:
f[s]: number of way to decode string s
starting from the least significant digit to the most significant digit:
recursive function: f[s[i ... end]] =
decode as current char s[i] + rest substring: s[i+1...end] (s[i] == 0? 0: f[s[i + 1... end]])
decode as current char and next char s[i ... i+1] + rest substring: s[i+2...end] (if we can both decode s[i...i+1] and s[i+2...end])
Code Time: O(n), Space O(n^2)
Last updated
Was this helpful?