面试题43:计算多少种译码方式(decode-ways)

2023-05-10,,

  这道题是非常典型的DP问题。按照DP的套路,关键是讨论出递推表达式,遍历过程中针对当前字符是否为'0'以及前一个字符为'0',分类讨论得出到目前字符为止最多有多少种译码方式?理清了递推表达式,代码是很简单的。

A message containing letters fromA-Zis 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.length();
vector<int> dp(n + , ); if (n == || s[] == '') return ; dp[] = ;
dp[] = ;
for (int i = ; i <= n; i++) {
if (s[i-] == '' && s[i - ] == '')
return ;
else if (s[i-] == '') {
dp[i] = dp[i - ];
}else if(s[i-] == ''){
if(s[i-] > '') return ;
dp[i] = dp[i-];
}else {
dp[i] = dp[i - ];
if (stoi(s.substr(i - , )) <= ) {
dp[i] += dp[i - ];
}
} }
return dp[n];
}
};

面试题43:计算多少种译码方式(decode-ways)的相关教程结束。

《面试题43:计算多少种译码方式(decode-ways).doc》

下载本文的Word格式文档,以方便收藏与打印。