题目:
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.
思路:
递推:dp[i]表示前 i 个数字的解码种数。
dp[i] = if(一)dp[i-1] + if(二)dp[i-2]
当 i 位置不为0,可加上 i - 1 位置的解。当当前位置和前一位置组成的两位数满足解码且高位不为0,可加上 i - 2 位置的解。
code:
class Solution {
public:
int numDecodings(string s) {
if(s.length() == 0) return 0;
vector<int> dp(s.length() + 1, 0);
dp[0] = 1;
for(int i = 0; i < s.length(); i ++)
{
dp[i + 1] = (s[i] != '0' ? dp[i] : 0) +
(i > 0 && s[i - 1] != '0' && atoi(s.substr(i - 1, 2).c_str()) <= 26 ? dp[i - 1] : 0);
}
return dp[s.length()];
}
};