LeetCode OJ: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.

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.

给一个数字,写出相应的解码方法,因为只需要给出解码的种数姐可以了,所以用dp比较简单就可以简单的解决了,答题的思路如下:

对于"123"来说,1只有一种,2有1, 2以及12两种,3 可以是 2自己的组合加上3 亦可以是23的组合加上1 自己的组合   ,一直类推,递推关系就找到了,代码如下所示:

 1 class Solution {
 2 public:
 3     int numDecodings(string s) {
 4         ret.resize(s.size());
 5         if(!s.size()) return 0;
 6         for(int i = 0; i < s.size(); ++i){
 7             if(i > 0){
 8                 string tmp = s.substr(i-1, 2);
 9                 if(tmp >= "10" && tmp <= "26")
10                     ret[i] += getRet(i - 2);
11                 if(s[i] >= '1' && s[i] <= '9')
12                     ret[i] += getRet(i - 1);
13             }else{
14                 if(s[0] >= '1' && s[0] <= '9')
15                     ret[i] = 1;
16             }
17         }
18         return ret[s.size() - 1];
19     }
20 
21     int getRet(int index)
22     {
23         if(index < 0)
24             return ret[0];
25         else
26             return ret[index];
27     }
28 private:
29     vector<int> ret;
30 };
原文地址:https://www.cnblogs.com/-wang-cheng/p/4964728.html