首页 > 其他 > 详细

Decode Ways

时间:2014-04-01 06:59:26      阅读:429      评论: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.

这些题目实现都没有考虑不合法的输入(non-num),考虑某个偏移i为止有多少种decode方式,会发现当前偏移i的方式取决于s[i] 和s[i - 1]的值以及偏移i - 1和i- 2时得到的decode的数目,所以这时一个一维的动态规划题目
如果s[i - 1]  == ‘1’ 或者 s[i - 1] == ‘2‘ && s[i] <= ‘6‘  (这代表所有1*以及20 - 26),则当前的ret[i]  先要加上ret[i-2] (因为i-1 和i构成一个字母);
如果s[i]不为‘0’,则s[i]可以单独构成一个字母,所有ret[i]这时还要加上ret[i - 1]的数目。

code逻辑很简单,直接看代码就行。


class Solution {
public:
    int numDecodings(string s) {
        int len = s.length();
        if (len == 0 || s[0] == ‘0‘) return 0;
        vector<int> ret(len + 1, 0);
        ret[0] = ret[1] = 1;
        for (int i = 2; i <= len; ++i) {
            if (s[i - 2] == ‘1‘ || (s[i - 2] == ‘2‘ && s[i - 1] <= ‘6‘)) {
                ret[i] += ret[i - 2];
            } 
            
            if (s[i - 1] != ‘0‘) ret[i] += ret[i - 1];
        }
        
        return ret[len];
    }
    

};


Decode Ways,布布扣,bubuko.com

Decode Ways

原文:http://blog.csdn.net/icomputational/article/details/22698511

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