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:
int numDecodings(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int length = s.size();
if(length<1)return 0;
int* dp = new int[length+1];
memset(dp, 0, sizeof(int)*(length+1));
dp[0] = 1;
if(s[0] == '0')dp[1] = 0;
else dp[1] = 1;
for(int i = 2; i <= length; ++i)
{
int num = stoi(s.substr(i-1,1));
if(num > 0)
dp[i] = dp[i-1];
num = stoi(s.substr(i-2,2));
if(num > 9 && num < 27)
dp[i] += dp[i-2];
}
int res = dp[length];
delete[] dp;
return res;
}

本文介绍了一种基于动态规划的算法,用于计算给定数字字符串的不同字母解码方式的数量。通过递推公式,文章详细解释了如何高效地解决该问题,并提供了完整的C++实现代码。

471

被折叠的 条评论
为什么被折叠?



