First, the topic
Given a string containing 26 letters, letters and numbers produce mappings, such as:
' A '-1
' B '--2
...
' Z '--26
If you give a bunch of numbers, how much is the encoding?
* Note: ' 12 ' can be encoded as "AB" and can also be encoded as "L".
Second, analysis
It can be seen that the purpose of the topic is to examine the dynamic planning, that is, each step may have two situations, is not like climbing the stairs? That's right.
There are two ways of thinking about this problem, but the idea is the same:
1. Traverse backwards from the past
(1), ans[0] = 1;
(2), if s[0] = ' 0 ', ans[1] = 0; otherwise ans[1] = 1;
(3), traverse judgment s[i-1] is equal to ' 0 ', 0 ans[i] = 0; otherwise equal to ans[i-1], and then determine whether the number of the next one is greater than 26, less than ans[i]= Ans[i] + ans[i-2]
2. Traverse from backward to forward
(1), ans[len] = 1;
(2), if s[len-1] = ' 0 ', ans[len-1] = 0; otherwise ans[len-1]= 1;
(3), traverse judgment s[i] is equal to ' 0 ', is 0 continue; otherwise determine whether the number with the following one is greater than 26, greater than ans[i] = ans[i+1], otherwise ans[i] = ans[i+1] + ans[i+2]
1, the positive sequence traversal method:
Class Solution {public: int numdecodings (string s) { int len = S.size (); if (len = = 0) return 0; int ans[len+1]; Ans[0] =1; if (s[0]! = ' 0 ') ans[1] = 1; else ans[1] = 0; for (int i=2;i<=len;i++) { if (s[i-1]! = ' 0 ') ans[i] = ans[i-1]; else ans[i] = 0; if (s[i-2] = = ' 1 ' | | (S[i-2] = = ' 2 ' && s[i-1] <= ' 6 ')) Ans[i] = Ans[i] + ans[i-2]; } return Ans[len];} ;
2. Reverse-order Traversal method:
Class Solution {public: int numdecodings (string s) { int len = S.size (); if (len = = 0) return 0; int ans[len+1]; memset (ans,0,len*sizeof (int)); Ans[len] =1; if (s[len-1]! = ' 0 ') ans[len-1] = 1; else ans[len-1] = 0; for (int i=len-2;i>=0;i--) { if (s[i] = = ' 0 ') continue; if (S[i] > ' 2 ' | | (S[i] = = ' 2 ' && s[i+1] > ' 6 ')) Ans[i] = ans[i+1]; else ans[i] = ans[i+1] + ans[i+2]; } return ans[0];} ;
Leetcode:decode Ways