LeetCode91. Decode Ways——动态规划

文章目录

一、题目

A message containing letters from A-Z can be encoded into numbers using the following mapping:

'A' -> "1"

'B' -> "2"

...

'Z' -> "26"

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:

"AAJF" with the grouping (1 1 10 6)

"KJF" with the grouping (11 10 6)

Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".

Given a string s containing only digits, return the number of ways to decode it.

The test cases are generated so that the answer fits in a 32-bit integer.

Example 1:

Input: s = "12"

Output: 2

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

Example 2:

Input: s = "226"

Output: 3

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

Example 3:

Input: s = "06"

Output: 0

Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").

Constraints:

1 <= s.length <= 100

s contains only digits and may contain leading zero(s).

二、题解

cpp 复制代码
class Solution {
public:
    int numDecodings(string s) {
        int n = s.size();
        vector<int> dp(n+1,0);
        dp[n] = 1;
        for(int i = n - 1;i >= 0;i--){
            if(s[i] == '0') dp[i] = 0;
            else{
                dp[i] = dp[i + 1];
                if(i + 1 < n && stoi(s.substr(i,2)) <= 26) dp[i] += dp[i+2];
            }
        }
        return dp[0];
    }
};
相关推荐
雾削木28 分钟前
mAh 与 Wh:电量单位的深度解析
开发语言·c++·单片机·嵌入式硬件·算法·电脑
__lost30 分钟前
小球在摆线上下落的物理过程MATLAB代码
开发语言·算法·matlab
8RTHT1 小时前
数据结构(七)---链式栈
数据结构
Ethon_王2 小时前
走进Qt--工程文件解析与构建系统
c++·qt
mit6.8242 小时前
[Lc_week] 447 | 155 | Q1 | hash | pair {}调用
算法·leetcode·哈希算法·散列表
Fency咖啡3 小时前
《代码整洁之道》第9章 单元测试 - 笔记
数据结构·b树
2501_906314323 小时前
优化无头浏览器流量:使用Puppeteer进行高效数据抓取的成本降低策略
开发语言·数据结构·数据仓库
C182981825753 小时前
项目中数据结构为什么用数组,不用List
数据结构
工藤新一¹3 小时前
C++/SDL进阶游戏开发 —— 双人塔防游戏(代号:村庄保卫战 13)
c++·游戏·游戏引擎·毕业设计·sdl·c++游戏开发·渲染库
jerry6093 小时前
优先队列、堆笔记(算法第四版)
java·笔记·算法