[LeetCode] 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.

问题:对给定纯数字字符串解码,求解法的可能情况有多少种。

注:0 开头的字符串算作无效, 例如, "02" 无法解码。

也是一道蛮典型的 DP 问题。

总的解码个数,等于对第一个数字单独解码的情况,加上对前两个数字一起解码的情况。

利用 vector<int> v 记录中间计算结果。 v[i] 表示 s[i...n] 的解码个数。

1     vector<int> v;
 2     
 3     int decode(string s, int p){
 4         
 5         if (v[p] != -1) {
 6             return v[p];
 7         }
 8         
 9         if (s[0] == '0') {
10             v[p] = 0;
11             return 0;
12         }
13         
14         if (s.size() == 1) {
15             v[p] = 1;
16             return 1;
17         }
18         
19         if (s.size() == 2) {
20             int tmp = 0;
21             if (s[1] != '0') {
22                 tmp++;
23             }
24             
25             if (stoi(s) <= 26) {
26                 tmp++;
27             }
28             v[p] = tmp;
29             return tmp;
30         }
31         
32         
33         int n1 = 0;
34         if (s[1] != '0') {
35             n1 = decode(s.substr(1), p+1);
36         }
37         
38         int n2 = 0;
39         if (stoi(s.substr(0, 2)) <= 26) {
40             n2 = decode(s.substr(2), p+2);
41         }
42         
43         int res = n1 + n2;
44         
45         v[p] = res;
46         return res;
47     }
48 
49 
50     int numDecodings(string s) {
51         vector<int> tmp(s.size() , -1);
52         
53         v = tmp;
54     
55         if(s.size() == 0){
56             return 0;
57         }
58         
59         int res = decode(s, 0);
60         
61         return res;
62     }

全部评论

相关推荐

不愿透露姓名的神秘牛友
06-23 18:34
点赞 评论 收藏
分享
流浪的神仙:无恶意,算法一般好像都得9硕才能干算法太卷啦
点赞 评论 收藏
分享
能干的三文鱼刷了100道题:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务