A message containing letters from A-Z is 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 "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
简单动规题。
1 class Solution { 2 public: 3 int numDecodings(string s) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int * a; 7 a = new int[s.size()+1]; 8 memset(a,0,(s.size()+1)*sizeof(int)); 9 if(s.size() == 0) 10 return 0; 11 a[0] = 1; 12 for(int i = 1; i <= s.size(); i++) 13 { 14 if(s[i-1] != '0') 15 a[i] += a[i-1]; 16 if(i -2 >= 0 && s[i-1] - '0' + 10 * (s[i-2] - '0') <= 26 && s[i-1] - '0' + 10 * (s[i-2] - '0') >= 10) 17 a[i] += a[i-2]; 18 } 19 return a[s.size()]; 20 } 21 };

浙公网安备 33010602011771号