LeetCode 91. Decode Ways

本文介绍了一种算法,用于计算给定数字串的不同字母解码方式的数量。使用动态规划方法,通过数组记录中间结果避免重复计算,实现高效求解。

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

91. Decode Ways

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.

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.

Analysis
这道题的意思就是让我们求所给字符串有多少种可能的组合。
我的做法是新建一个数组res,而且数组的程度比字符串多1。res[i]表示表示当前s[i-1]可能的组合数。
显示当s[i-1]=0时,就说明必定是要与前一个数字进行组合,所以s[i-1]!=0时,res[i] = res[i-1。然后在通过判断和前一个数字的组合是否超过26,如果没有超过26,就 res[i]+=res[i-2]。
最后返回结果。

Code

class Solution {
public:
    int numDecodings(string s) {
        if(s.size() == 0) return 0;
        if(s[0] == '0') return 0;

        int len = s.size();
        int res[len+1];
        res[0] = 1;
        res[1] = 1;

        for(int i = 2; i<len+1;++i ){
            if(s[i-1] != '0' ) res[i] = res[i-1];
            else res[i] = 0;
            if(s[i-2] == '1' || (s[i-2] == '2' && s[i-1] <='6')) res[i]+=res[i-2];
        }

        return res[len];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值