91 Decode Ways
Last updated
Last updated
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.
The Idea: This problem can be reduced to solving subproblems. For example, the input 12345
can be reduced to solving numDecodings(12345) = numDecodings(1234) + numDecodings(123)
. The way to interpret this is that the tail end of the input 5
and 45
can interpreted to have two unique encodings. In this case of course, 45
would return 0 because it is out of bounds of the alphabetical mapping [1-26]
. There are also a few other edge cases to consider, and I have highlighted then in the recursion trees below. The general idea is to not descend down a subtree if the interpretation of the tail end of the string isn't valid.
You may also notice some reoccurring subtrees, in which case, we use memiozation to save their results.
Complexity: O(N) time and space