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

【LeetCode】091. Decode Ways

时间:2017-05-06 21:46:54      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:win   back   class   ids   div   ++   while   har   from   

题目:

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.

题解:

  这个题与之前的爬楼梯有些类似,只是有了0和26的限制判断。

Solution 1 ()

class Solution {
public:
    int numDecodings(string s) {
        if(s.empty() || s.size()>1 && s.front() == 0) return 0;
        vector<int> dp(s.size()+1, 0);
        dp[0] = 1;
        for(int i=1; i<dp.size(); i++) {
            if(s[i-1] == 0) dp[i] = 0;
            else dp[i] = dp[i-1];
            if(i>1 && (s[i-2] == 1 || s[i-1] <= 6 && s[i-2] == 2))
                dp[i] += dp[i-2];
        }    
        return dp.back();
    }
};

Solution 2 ()

class Solution {
public:
    int numDecodings(string s) {
        if(s.empty() || s.front() == 0) return 0;
        // r2: decode ways of s[i-2] , r1: decode ways of s[i-1]
        int r1 = 1, r2 = 1;
        for(int i=1; i<s.size(); i++) {
        // zero voids ways of the last because zero cannot be used separately
            if(s[i] == 0)  r1 = 0;
        // possible two-digit letter, so new r1 is sum of both while new r2 is the old r1
            if(s[i-1] == 1 || s[i-1] == 2 && s[i] <= 6) {
                r1 = r2 + r1;
                r2 = r1 - r2;
            }
        // one-digit letter, no new way added
            else r2 = r1;
        }    
        return r1;
    }
};

 

【LeetCode】091. Decode Ways

标签:win   back   class   ids   div   ++   while   har   from   

原文地址:http://www.cnblogs.com/Atanisi/p/6818140.html

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