Decode Ways
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.
思路:
典型的动规,用n[i]表示从i到末尾的表示法,然后对于每一个i,判断s[i]和s[i]+s[j]能否解码,再分别加上n[i+1]和n[i+2]即可。
代码:
1 int numDecodings(string s) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 int l = s.length(); 5 if(l == 0) 6 return 0; 7 if(l == 1) 8 return s[0] > '0'; 9 int ways[l]; 10 int i; 11 ways[l-1] = s[l-1] > '0'; 12 if(s[l-2] == '0') 13 ways[l-2] = 0; 14 else{ 15 if((s[l-2]-'0')*10+s[l-1]-'0' <= 26) 16 ways[l-2] = ways[l-1] + 1; 17 else 18 ways[l-2] = ways[l-1]; 19 } 20 for(i = l-3; i >= 0; i--){ 21 if(s[i] == '0'){ 22 ways[i] = 0; 23 continue; 24 } 25 int tmp = (s[i]-'0')*10+s[i+1]-'0'; 26 if(tmp <= 26) 27 ways[i] = ways[i+1] + ways[i+2]; 28 else 29 ways[i] = ways[i+1]; 30 } 31 return ways[0]; 32 }
第二遍
1 int numDecodings(string s) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 int l = s.length(); 5 if(l == 0) 6 return 0; 7 if(l == 1) 8 return s[0]>'0'; 9 int result[l+1]; 10 result[l-1] = s[l-1]>'0'; 11 result[l] = 1; 12 for(int i = l-2; i >= 0; i--){ 13 if(s[i] == '0') 14 result[i] = 0; 15 else{ 16 int tmp = 10*(s[i]-'0')+s[i+1]-'0'; 17 if(tmp <= 26) 18 result[i] = result[i+1]+result[i+2]; 19 else 20 result[i] = result[i+1]; 21 } 22 } 23 return result[0]; 24 }