LeetCode 91 Decode Ways 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 6is 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];     } };