问题描述:

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.



思路:使用DP解决此问题时,主要需要考虑0的存在,比如'00'输出0,'10'输入1,110输出2等等。该问题类似爬楼梯问题,设a[i]为前i个字符构成的解,则达到a[i]有两种方式,一种是从a[i-1]到达a[i],此时需要满足s[i]所代表的数不为0,;另一种是从a[i-2]到a[i],其中s[i-1]和s[i]构成的十进制数需要在1~26之间并且s[i-1]所代表的数需要大于0,即十进制数01,02,...09是不满足条件的。另外还需要注意初始值的a[0]和a[1]的设定


代码:

#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
class Solution {
public:
    int numDecodings(string s) {
        int len=s.length();
        int a[10000];
        if(len==0) return 0;
        a[0]=s[0]-'0'>0?1:0;
        if(len>=2){
            int num=(s[0]-'0')*10+s[1]-'0';
            a[1]=0;
            if(num<=26&&num>0&&s[0]-'0'>0) a[1]+=1;
            if(s[1]-'0'>0&&a[0]>0) a[1]+=1;

            for(int i=2;i<len;i++){
                num=(s[i-1]-'0')*10+s[i]-'0';
                a[i]=0;
                if(num<=26&&num>0&&s[i-1]-'0'>0) a[i]+=a[i-2];
                if(s[i]-'0'>0) a[i]+=a[i-1];
            }
        }
        return a[len-1];
    }
};


int main()
{
    string s="110";
    cout<<(new Solution())->numDecodings(s);
}


Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐