[Leetcode] Decode Ways
Decode Ways 题解
题目来源:https://leetcode.com/problems/decode-ways/description/
Description
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.
Example
Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
The number of ways decoding "12" is 2.
Solution
class Solution {
public:
int numDecodings(string s) {
if (s.empty())
return 0;
int size = s.size();
vector<int> dp(size + 1, 0);
dp[size] = 1;
dp[size - 1] = s[size - 1] == '0' ? 0 : 1;
for (int i = size - 2; i >= 0; i--) {
if (s[i] == '0') {
continue;
} else {
if (s[i] == '1' || (s[i] == '2' && s[i + 1] <= '6'))
dp[i] = dp[i + 1] + dp[i + 2];
else
dp[i] = dp[i + 1];
}
}
return dp[0];
}
};
解题描述
这道题题意是,给出一个数字串,求数字串能解码出多少种字母序列。这里给出的是DP的解法,其中关键就是求出可能会有2种情况的解码方式。讨论区给出的详细的解释是:
- 给出例子
123XXXX - 在
1这个位置上,向前探1位可以构成12,符合解码字符要求 - 这样
12可以被拆分为1 2或12,记1所在位置为i- 对
1 2而言,前面的解码方法对应从2开始的解法,有dp[i + 1]种 - 对
12而言,前面的解码方法对应从3开始的解法,有dp[i + 2]种
- 对
- 所以
dp[i] = dp[i + 1] + dp[i + 2]

浙公网安备 33010602011771号