首页 > 代码库 > LeetCode91 Decode Ways

LeetCode91 Decode Ways

题目:

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. (Medium)

 

分析:

开始想到的就是暴力搜索,但是超时了,所以考虑用动态规划来做。

符合单序列动态规划的特点,所以

1. 状态:dp[i]表示前i个字符组成的子串可能的解码方式。

2. 初始化:

  dp[0] = 1, dp[1] = 1(s[0] != ‘0‘,因为没有0这个对应数字)

3. 递推关系:

一般情况下:

  if s[i - 1]与s[i -2]组成的在“1” ~“26”范围内, dp[i] = dp[i - 1] + dp[i - 2];

                    else, dp[i] = dp[i - 1];

但要注意的是,如果s[i - 1] == ‘0‘需要特殊处理,当s[i - 2] == ‘1‘ || ‘2‘时, dp[i] = dp[i - 2]

                      否则,则说明这个0没有对应位,这个字符串无法解码,直接返回0;

4.结果: dp[s.size()];

代码:

 1 class Solution {
 2 public:
 3     int numDecodings(string s) {
 4         if (s.size() == 0) {
 5             return 0;
 6         }
 7         int dp[s.size() + 1];
 8         dp[0] = 1;
 9         if (s[0] != 0) {
10             dp[1] = 1;
11         }
12         for (int i = 2; i <= s.size(); ++i) {
13             if (s[i - 1] == 0) {
14                 if (s[i - 2] == 1 || s[i - 2] == 2) {
15                     dp[i] = dp[i - 2];
16                     continue;
17                 }
18                 else {
19                     return 0;
20                 }
21             }
22             if (s[i - 2] == 1 || (s[i - 2] == 2 && s[i - 1] <= 6) ) {
23                 dp[i] = dp[i - 1] + dp[i - 2];
24             } 
25             else {
26                 dp[i] = dp[i - 1];
27             }
28         }
29         return dp[s.size()];
30     }
31 };

 

 

 

 

2. 递推关系:

LeetCode91 Decode Ways