Decode Ways(如何解码) 【leetcode】

来源:互联网 发布:好看的淘宝金酷娃玩具 编辑:程序博客网 时间:2024/06/05 14:10

题目: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怎么处理状态半天理不清。

就从后开始遍历,如果当前位置是零,由于不能有两位数前置零,就没有继承的状态。

因此dp就容易推了。


class Solution {public:    int numDecodings(string s) {        if(s.size()==0)return 0;        vector<int>dp;        dp.resize(s.size()+1);        int len=s.size();        dp[len]=1;        int num=0;        for(int i=len-1;i>=0;--i)        {            if(s[i]!='0')            {                dp[i]=dp[i+1];                if((s[i]=='1')||(s[i]=='2'&&s[i+1]<='6'))                {                    if(i<len-1)dp[i]+=dp[i+2];                }            }            else             {                dp[i]=0;                            }        }        return dp[0];            }};