[Leetcode] Decode Ways

本文探讨了一种特定的编码方式,其中字母A至Z被映射为数字1至26。文章详细介绍了如何确定一个由数字组成的编码消息可以解码成不同字母组合的方式总数。通过动态规划的方法,给出了高效的解决方案,并对比了深度搜索的低效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

动态规划,想法跟Climbing Stairs想法一样,形式相同,但是加了一些限制,不是所有情况下都能后传递,所以要写两个判断函数。

 1 class Solution {
 2 public:
 3     bool isLegal(char digit) {
 4         return digit != '0';
 5     }
 6     
 7     bool isLegal(char digit1, char digit2) {
 8         return digit1 == '1' || (digit1 == '2' && digit2 < '7');
 9     }
10     
11     int numDecodings(string s) {
12         if (s.length() == 0) return 0;
13         if (s.length() == 1) return isLegal(s[0]) ? 1 : 0;
14         vector<int> dp(s.length(), 0);
15         if (isLegal(s[0]))  dp[0] = 1;
16         if (isLegal(s[0]) && isLegal(s[1]))  dp[1] = 1;
17         if (isLegal(s[0], s[1])) dp[1] += dp[0];
18         for (int i = 2; i < s.length(); ++i) {
19             if (isLegal(s[i])) dp[i] += dp[i-1];
20             if (isLegal(s[i-1], s[i])) dp[i] += dp[i-2];
21         }
22         return dp[s.length() - 1];
23     }
24 };

最开始想到是的深搜,超时了。看来以后在考虑问题时要把动规的优先级调到深搜广搜的前面。

 1 class Solution {
 2 public:
 3     void getDecode(string &s, int idx, int &res) {
 4         if (idx == s.length()) {
 5             ++res;
 6             return;
 7         }
 8         int val = s[idx] - '0';
 9         getDecode(s, idx + 1, res);
10         if (idx + 1 < s.length()) {
11             val *= 10;
12             val += s[idx+1] - '0';
13             if (val < 27) {
14                 getDecode(s, idx + 2, res);
15             }
16         }
17     }
18     
19     int numDecodings(string s) {
20         int res = 0;
21         getDecode(s, 0, res);
22         return res;
23     }
24 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值