A-Z encoded as 1-26. Given a string of digits s, return the number of ways to decode it.
dp[i] = decodings of first i chars. Single digit s[i-1] (1-9) adds dp[i-1] ways. Two digits s[i-2..i-1] (10-26) adds dp[i-2] ways. Sum both when valid.
Trying every way to split the string recursively repeats the same suffixes many times. Like climbing stairs, each position can be reached by one digit or by two.
Let dp of i be the number of ways to decode the first i characters. The empty prefix has exactly 1 way, so dp of 0 is 1. If the single digit at position i is not 0, add dp of i −1. If the last two digits form a number from 10 to 26, add dp of i minus 2. Zeros are the tricky part, because 0 alone is not a letter.
One digit or two digits, just like one step or two. A 0 can only be used as part of 10 or 20.
Run the animation above on your own input, or watch the 1:59 video explanation of Decode Ways with a dry run and Java code.