[leetcode] Decode Ways

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.
 
 
方案:
算法:动态规划;

函数设计:
     我们使用数组f[i], 存储长度为 i 的 s 串可以被翻译的方法数。
     char类型的cur表示长度为i的s'的最后一个字符,pre表示长度为i的s'的倒数第二个字符。
     (1)当s为空时,返回0;
     (2)当s不为空,但s[0] = '0'时 , 返回 0。 因为此时,s不可能被翻译为A-Z组成的字符串。
     (3)当s不为空,且开始字母不为‘0’时,初始化f[0] = 1, f[1] = 0;
                  a,当pre = '1', 且 cur != '0'时, f[n] = f[n-1] + f[n-2]; 因为此时字符串i必然为...1x = ...1 + x, 或者 ...1x = ... + 1x;
                      由 ...1 + x的方式组成 ...1x时,译码方法数等于f[n-1];
                      由 ... + 1x的方式组成 ...1x时,译码方法数等于f[n-2];
                  b,当pre = '2', 且 cur 的取值为{'1', '2', '3', '4', '5', '6'}的其中之一时,f[n] = f[n-1] + f[n-2];原理同上。
                  c,当cur = '0' 时,
                      c1, 如果pre = '1' 或者 pre = '2'时,译码方法数必然等于 f[n-2],因为此时译码方式必然为...+ 10 或者 ... + 20。 不可能为...1 + 0这样的方式。
                      c2, 如果pre 不为'1','2', 译码方法数必然为0
                  d,其余情况译码方法 f[n] = f[n-1];
 
 
 1 class Solution
 2 {
 3 public:
 4   int numDecodings(string s)
 5   {
 6     if(s.empty() || s[0] == '0') return 0;
 7 
 8     int f[s.size()];
 9     char pre = s[0], cur;
10 
11     f[0] = 1;
12     f[1] = 1;
13     for(int i=2; i<=s.size(); i++)
14     {
15       cur = s[i-1];
16 
17       if(pre == '1' && cur != '0')
18         f[i] = f[i-1] + f[i-2];
19       else if(pre == '2' && '1' <= cur && cur <= '6')
20         f[i] = f[i-1] + f[i-2];
21       else if(cur == '0')
22       {
23         if(pre == '1' || pre == '2')
24         {
25           f[i-1] = f[i-2];
26           f[i] = f[i-2];
27         }
28         else
29           return 0;
30       }
31       else
32         f[i] = f[i-1];
33 
34       pre = cur;
35     }
36 
37     return f[s.size()];
38   }
39 };

 

posted @ 2015-01-26 18:51  imKirin  阅读(170)  评论(0编辑  收藏  举报