码迷,mamicode.com
首页 > 其他好文 > 详细

Decode Ways

时间:2015-07-15 13:18:24      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:string   leetcode   

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;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

Decode Ways

标签:string   leetcode   

原文地址:http://blog.csdn.net/u012365383/article/details/46890627

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!