A message containing letters from A-Z is being encoded to numbers using the following mapping:‘A‘ -> 1‘B‘ -> 2...‘Z‘ -> 26Given 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.
Difficulty: 90. A very good one-dimensional DP question, referring to the practices on the Internet.
When we see this quantity, we can easily think of dynamic planning to store the previous information, and then iterate to get the final result.
The number of RES [I] We maintain is the number of Resolution Methods for the first I number. Let's look at the recursive formula in two ways: the first kind of newly added numbers or their own comparison represents a character, then the resolution method res [I-1], the second kind is the newly added number and the previous number into a character, the resolution method is res [I-2] (because the last character is a combination of itself ). Of course, we need to determine whether the two cases mentioned above can be written into one character, that is, the range. If there is a corresponding parsing method, if not, it is 0. The final result is to add the Resolution Methods corresponding to the two cases. Here we can divide the range into several intervals:
(1) 00, 30, 40... 90: res [I] = 0 (no parsing method available );
(2) 10, 20: res [I] = res [I-2] (only in the second case );
(3) 11-19, 21-26: res [I] = res [I-1] + Res [I-2] (both cases are feasible );
(4) 01-09, 27-99: res [I] = res [I-1] (only available in the first case );
The recurrence formula is obtained according to the above rules. Next we only need to perform a scan and then obtain the Maintenance Quantity in sequence. The time complexity of the algorithm is O (n ). In space, we can see that we only need the first two historical information each time, so we only need to maintain three variables and then iterate and assign values. Therefore, the space complexity is O (1 ).
Note the initial values.
1 public class Solution { 2 public int numDecodings(String s) { 3 if (s==null || s.length()==0 || s.charAt(0)==‘0‘) { 4 return 0; 5 } 6 int num1 = 1; 7 int num2 = 1; 8 int num3 = 1; 9 for (int i=1; i<s.length(); i++) {10 if (s.charAt(i) == ‘0‘) {11 if (s.charAt(i-1) == ‘1‘ || s.charAt(i-1) == ‘2‘) {12 num3 = num1;13 }14 else return 0;15 }16 else {17 if (s.charAt(i-1) == ‘0‘ || s.charAt(i-1) >= ‘3‘) {18 num3 = num2;19 }20 else if (s.charAt(i-1)==‘2‘ && (s.charAt(i) ==‘7‘||s.charAt(i)==‘8‘||s.charAt(i)==‘9‘)) {21 num3 = num2;22 }23 else num3 = num2 + num1;24 }25 num1 = num2;26 num2 = num3;27 }28 return num2;29 }30 }
Leetcode: Decode ways