Question
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.
class Solution {
public:
int numDecodings(string s) {
int n = s.size();
if(0 == n)
{
return 0;
}
vector<int> record(s.size() + 1, -1); // 记录已经保存的结果
return numDecodingsByDP(s, record);
}
int numDecodingsByDP(string s, vector<int>& record)
{
/**
* 采用动态规划解
* record:作为记录表
* 状态转移方程:
* f(n) = tag1 * f(n - 1) + tag2 * f(n - 2);
* tag1 = c(n) == '0'? 0:1;
* tag2 = <n,n-1> can be decoded? 1: 0;
* 初始状态:
* f(0) = 1; f(1) = 1;
**/
int n = s.size();
int tmpR = record.at(n);
if(tmpR >= 0)
{
return tmpR;
}
if(n == 1)
{
tmpR = s.at(0) == '0'? 0:1;
record.at(n) = tmpR;
return tmpR;
}
if(n == 0)
{
record.at(0) = 1;
return 1;
}
char c_n = s.at(0);
char c_n1 = s.at(1);
int str2num = (c_n - '0') * 10 + (c_n1 - '0');
bool tag1 = c_n > '0'; // 首字母不为0
bool tag2 = str2num <= 26 && tag1 == 1; // 首字母不为0,且值小于27
int num = 0;
if(tag1 && tag2)
{
num = numDecodingsByDP(s.substr(1), record) + numDecodingsByDP(s.substr(2), record);
}else if(tag1)
{
num = numDecodingsByDP(s.substr(1), record);
}else if(tag2)
{
num = numDecodingsByDP(s.substr(2), record);
}
record.at(n) = num;
return num;
}
};