A message containing letters from was A-Z
being encoded to numbers using the following mapping:
' A '-1 ' B '-2 ... ' Z '-26
Given an encoded message containing digits, determine the total number of ways to decode it.
For example,
Given encoded message "" "
, it could be decoded as "AB"
(1 2) Or "L"
(a).
The number of ways decoding is "12"
2.
Class Solution {BOOL Judge (int i) {return i > 0 && i<3; } bool Judge (int I,int j) {int t = i*10 + j; if (t>26 | | t <=10) return false; return true; }public:int numdecodings (string s) {int n = s.size (); int a[n]; for (int i = 0;i<n;++i) {A[i] = s[i]-' 0 '; } if (n = = 0) return 0; The first number is 0 if (a[0] = = 0) return 0; if (n = = 1) return 1; int dp[s.size ()]; Dp[0] = 1; if (a[1]! = 0) Dp[1] = Judge (a[0],a[1])? 2:1; else{if (a[0]<=0 | | a[0] > 2) return 0; else dp[1] = 1; } if (n==2) return dp[1]; for (int i = 2; i<n; ++i) {if (a[i]! = 0) Dp[i] = Dp[i-1] + (judge (a[i-1],a[i))? Dp[i-2]: 0); else if (a[i-1]<=0 | | a[i-1] > 2) return 0; else dp[i] = dp[i-2]; } return dp[n-1]; }};
At the beginning did not consider the inside will appear 0, then is very silly than the submission of ...
can define DP[N],A[N]
The pseudo code is as follows,
If a[i] = = 0
If A[I-1] greater than 0 less than 3//such a[i-1] and a[i] can form a letter
Dp[i] = dp[i-2]//In this case, the number of species can only be equal to dp[i-2], the number of species does not increase
Else
Dp[i] = 0//illegal in other cases
Else
If a[i-1]<=0, greater than two
Dp[i] = dp[i-1]//New letters can only be one case
Else
Dp[i] = dp[i-1]+dp[i-2]//Add new letters as a case, you can also add new letters and old letters as a situation
Take a look at the Big Brother's answer
int numdecodings (string s) { if (!s.size () | | | S.front () = = ' 0 ') return 0; R2:decode ways of S[i-2], r1:decode ways of s[i-1] int r1 = 1, r2 = 1; for (int i = 1; i < s.size (), i++) { //zero voids ways of the last because zero cannot is used separately if ( S[i] = = ' 0 ') r1 = 0; Possible two-digit letter, so new R1 are sum of both while new R2 are the old R1 if (s[i-1] = = ' 1 ' | | s[i-1] = = ' 2 ' && s[i] <= ' 6 ') { r1 = r2 + r1; r2 = r1-r2; } One-digit letter, no new to added else { r2 = r1; } } return R1;}
That's a lot of information. The space is O (1), because only the first two values need to be stored.
[LC] Decode Ways