Decode Ways

11 篇文章 0 订阅
9 篇文章 0 订阅

Question

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.

My Solution

class Solution {
public:
    int numDecodings(string s) {
        int n = s.size();
        if(0 == n)
        {
            return 0;
        }
        vector<int> record(s.size() + 1, -1);  // 记录已经保存的结果
        return numDecodingsByDP(s, record);
    }
    
    int numDecodingsByDP(string s, vector<int>& record)
    {
        /**
         * 采用动态规划解
         * record:作为记录表
         * 状态转移方程:
         * f(n) = tag1 * f(n - 1) + tag2 * f(n - 2);
         * tag1 = c(n) == '0'? 0:1;
         * tag2 = <n,n-1> can be decoded? 1: 0;
         * 初始状态:
         * f(0) = 1; f(1) = 1;
         **/
         
         int n = s.size();
         int tmpR = record.at(n);
         if(tmpR >= 0)
         {
             return tmpR;
         }
         if(n == 1)
         {
             tmpR = s.at(0) == '0'? 0:1;
             record.at(n) = tmpR;
             return tmpR;
         }
         if(n == 0)
         {
             record.at(0) = 1;
             return 1;
         }
         
        
         char c_n = s.at(0);
         char c_n1 = s.at(1);
         int str2num = (c_n - '0') * 10 + (c_n1 - '0');
         bool tag1 = c_n > '0';    // 首字母不为0
         bool tag2 = str2num <= 26 && tag1 == 1; // 首字母不为0,且值小于27
         int num = 0;
         if(tag1 && tag2)
         {
             num = numDecodingsByDP(s.substr(1), record) + numDecodingsByDP(s.substr(2), record);
         }else if(tag1)
         {
             num = numDecodingsByDP(s.substr(1), record);
         }else if(tag2)
         {
             num = numDecodingsByDP(s.substr(2), record);
         }
         record.at(n) = num;
         return num;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值