19.2.23 [LeetCode 91] Decode Ways

Posted TobicYAL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19.2.23 [LeetCode 91] 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 a non-empty string containing only digits, determine the total number of ways to decode it.

Example 1:

Input: "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

题意

输出一串数字可能的解读方式,这串数字的解读只能由1~26组成

题解

记忆性递归,好像挺慢的

技术图片
 1 class Solution {
 2 public:
 3     vector<int>mark;
 4     int cnt(string s) {
 5         int one = s[0] - 0, two = 0, ans = 0, l = s.length();
 6         if (one == 0)return 0;
 7         if (mark[l] != -1)return mark[l];
 8         if (l > 1)two = one * 10 + s[1] - 0;
 9         else if (l == 0)return 1;
10         ans += cnt(s.substr(1));
11         if (two <= 26 && two >= 1)
12             ans += cnt(s.substr(2));
13         mark[l] = ans;
14         return ans;
15     }
16     int numDecodings(string s) {
17         int l = s.length();
18         mark = vector<int>(l + 1, -1);
19         return cnt(s);
20     }
21 };
View Code

于是dp,o(n)的

技术图片
 1 class Solution {
 2 public:
 3     int numDecodings(string s) {
 4         int l = s.length();
 5         vector<int>dp(l + 1, 0);
 6         dp[0] = 1;
 7         if (s[0] - 0 != 0)dp[1] = 1;
 8         for (int i = 1; i < l; i++) {
 9             int one = s[i - 1] - 0, two = (s[i] - 0) + one * 10;
10             if (one != 0 && two <= 26 && two >= 1)
11                 dp[i+1] +=dp[i - 1];
12             if(s[i]!=0)
13                 dp[i+1] += dp[i];
14         }
15         return dp[l];
16     }
17 };
View Code

以上是关于19.2.23 [LeetCode 91] Decode Ways的主要内容,如果未能解决你的问题,请参考以下文章

19.2.23 [LeetCode 85] Maximal Rectangle

leetcode 91. Decode Ways 解码方法(中等)

LeetCode_Dec_2nd_Week

LeetCode_Dec_1st_Week

LeetCode_Dec_2nd_Week

LeetCode_Dec_3rd_Week