ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

LeetCode 91 Decode Ways DP

2022-05-10 05:31:06  阅读:182  来源: 互联网

标签:10 26 int text into Decode 91 LeetCode dp


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.

Solution

设 \(dp[i]\) 表示以下标 \(i\) 结尾的字符串的方案数,这里的 \(1\leq i\leq n\),所以对于字符串的下标,对应为 \(i-1\). 对于空串,即

\[dp[0]=1 \]

对于当前位置 \(i\),有两种方法:第一种就是以 \(i\) 的单独字母添加到后面:

\[dp[i]+=dp[i-1], \text{if }s[i-1]!=0 \]

第二种则是以 \(i-1,i\) 两个位置的字符进行拼凑,限制即为:无前导零且小于等于26:

\[dp[i]+=dp[i-2], \text{if }s[i-2]!=0\text{ and } 10(s[i-2]-'0')+s[i-1]\leq 26 \]

点击查看代码
class Solution {
private:
    int dp[104];
public:
    int numDecodings(string s) {
        dp[0]=1;
        int n = s.size();
        for(int i=1;i<=n;i++){
            if(s[i-1]!='0')dp[i]+=dp[i-1];
            if((i-2>=0) && (s[i-2]!='0') && (10*(s[i-2]-'0')+s[i-1]-'0' <=26) )dp[i]+=dp[i-2];
        }
        return dp[n];
    }
};

标签:10,26,int,text,into,Decode,91,LeetCode,dp
来源: https://www.cnblogs.com/xinyu04/p/16251958.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有