Decode Ways

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]=1,dp[1]=1(当s[0]!='0');dp[1]=0(s[0]=='0')

状态转移方程dp[i]+=dp[i-1](1~9);dp[i]+=dp[i-2](10~26);

class Solution {

public:

    int numDecodings(string s) {

        int n=s.size();

        if(n<=0)

            return 0;

        vector<int> dp(n+1,0);

        dp[0]=1;

        if(s[0]=='0')

            dp[1]=0;

        else

            dp[1]=1;

        for(int i=2;i<=n;i++)

        {

            int num=stoi(s.substr(i-1,1));

            if(num>0 && num<=9)

                dp[i]+=dp[i-1];

            num=stoi(s.substr(i-2,2));

            if(num>=10&&num<=26)

                dp[i]+=dp[i-2];

        }

        return dp[n];

    }

};

 

你可能感兴趣的:(decode)