Problem
A message containing letters from A-Z is being encoded to numbers using the following mapping:
1 | |
Given a non-empty string containing only digits, determine the total number of ways to decode it.
Example 1:
1 | |
Example 2:
1 | |
Explanation
-
We can use dynamic programming to solve this problem.
-
Dynamic state is a one dimensional array,
dp[s.length()+1], and itsiindex element is the decode ways of the substring choosing the firsticharacter. For example, let input strings=123, thendp[1]is the decode way of1;dp[2]is the decode way of12;dp[3]is the decode way of123; -
Dynamic init is
dp[1]=1,dp[0]=1because later we want the dynamic function to bedp[i] = dp[i-1] + dp[i-2], sodp[2] = dp[1] + dp[0], so we need to setdp[0]to some value,dp[0]is 1 because in general case, for example strings="12", we know the decode way is 2;s="1", we know the decode way is 1, so we setdp[1]=1, sodp[0]=1. -
Dynamic function in general case is
dp[i] = dp[i-1] + dp[i-2]. For example,s = "123", ifiis iterating at character 3, then we can think of 3 as a group, 12 as another group, in this cases = "123"its decode way is the same the decode way ofs=12, in other word,dp[i] = dp[i-1]. Beside this, we can think of 23 as a group, 1 as another group, in this case, its decode way is the same whens=1, in other word,dp[i] = dp[i-2]. -
There are some special case of the above dynamic function. If the string is “120”, the current iterated element is 0, then we cannot think of 0 as a group, we need to consider “20” as a group, 1 as another group, so
dp[i] = dp[i-2]. Also, if the string is “130” or “100”, then we cannot think of “0”, “30”, or “00” as a group, there is actually no way to decode such string. One more special case is whens=103, we can think of3as a group and10as another group, sodp[i]=dp[i-1], but we cannot think of03as group, so we cannot usedp[i]=dp[i-2]. -
Dynamic result is
dp[s.length()], which means return the decode way when we choose all the elements.
Solution
1 | |