LintCode_512 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.

Example

Given encoded message 12, it could be decoded as AB (1 2) or L (12).
The number of ways decoding 12 is 2.


思路是通过DFS来解决, 注意一些边界条件。

但是这样仍然引入的大量重复计算,所以过程中将已经计算过的string存起来, 节省时间, 类似dp的思想:


class Solution {
public:
    /**
     * @param s a string,  encoded message
     * @return an integer, the number of ways decoding
     */
    int numDecodings(string& s) {
        // Write your code here
        unordered_map<string, int> map;
        int res = numDecodings_helper(s, map);
        return res;
    }
    
    int numDecodings_helper(string& s, unordered_map<string, int>& map) {
        if (s[0] == '0') {
            return 0;
        }
        if (s.size() <= 1) {
            return s.size();
        }
        if (map.find(s) != map.end()) {
            return map[s];
        }
        int res1 = 0;
        int res2 = 0;
        if (s[1] != '0') {
           string s1 = s.substr(1, s.size() - 1);
           res1 = numDecodings_helper(s1,map);
        }
        string t = s.substr(0,2);
        if (t <= "26") {
            if (s.size() >= 3) {
                string s2 = s.substr(2, s.size() - 2);
                res2 = numDecodings_helper(s2, map);
            } else {
                res2 = 1;
            }
        }
        map[s] = res1 + res2;
        return res1 + res2;
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值