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(n-1)+f(n-2)      s[1]>'0'且s[0]=='1'或s[0]=='2',s[1]<'7'
f(n)={
         f(n-1)                 其它

还想侥幸试试,结果肯定超时,既然超时那就DP吧,直接跟斐波那契一样,bottom-up来搞。代码:

 1     int numDecodings(string s) {
 2         int len = s.length();
 3         if(len==0||s[0]=='0') return 0;
 4         if(len==1) return s[0]>'0'?1:0;
 5         int n_1,n_2,result,j=len-1;
 6         n_1=s[j]>'0'?1:0;
 7         for(j-=1;j>=0;j--){
 8             if(s[j]<'3'&&s[j]>'0'){
 9                 if(s[j+1]>'0'&&((s[j]=='2'&&s[j+1]<'7')||s[j]=='1')){
10                     result = n_1+(j==len-2?1:n_2);
11                 }
12                 else if(s[j+1]=='0'){
13                     result = (j==len-2?1:n_2);
14                 }
15                 else{
16                     result = n_1;
17                 }
18             }
19             else if(s[j+1]=='0'){
20                 return 0;
21             }
22             else{
23                 result = n_1;
24             }
25             n_2=n_1;
26             n_1=result;
27         }
28         return result;
29     }

28ms pass.中间判断时,若发现没办法解了直接返回0就行了,例如,2001之类,还有字符串为空或以0开头就直接返回0。

posted @ 2013-12-15 15:32  月窟仙人  阅读(139)  评论(0编辑  收藏  举报