首页 > 其他 > 详细

Decode Ways

时间:2014-07-06 14:43:16      阅读:309      评论:0      收藏:0      [点我收藏+]
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 Ways,布布扣,bubuko.com

Decode Ways

原文:http://www.cnblogs.com/awy-blog/p/3825529.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!