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,1,然后由0,1计算得到后面的数·······
class Solution { public: int numDecodings(string s) { int len=s.size(); if(len==0||s[0]=='0') return 0; int num; int res; if(len==1) num =s[0]-'0'; else if(len==2) num=10*(s[0]-'0')+s[1]-'0'; if(num==0) return 0; else if(num<=10) return 1; else if(num>10&&num<=26) return 2; else if(num>26&&num<=99) return 1; res=max(numDecodings(s.substr(0,1))+numDecodings(s.substr(1,len)), numDecodings(s.substr(0,2))+numDecodings(s.substr(2,len))); return res; } };
正确的做法应该是这样的:
class Solution { public: int numDecodings(string s) { int len=s.size(); if(len==0) return 0; else if(len==1) return s[0]!='0'?1:0; else if(len==2) return (s[0]!='0'&&s[1]!='0'?1:0)+(s[0]!='0'&&((10*(s[0]-'0')+s[1]-'0')<=26)?1:0); int* flag=new int[len]; flag[0]=s[0]!='0'?1:0; flag[1]=(s[0]!='0'&&s[1]!='0'?1:0)+(s[0]!='0'&&((10*(s[0]-'0')+s[1]-'0')<=26)?1:0); for(int i=2;i<len;i++) { flag[i]=0; if(s[i]!='0') { flag[i]+=flag[i-1]; } if(s[i-1]!='0'&&(10*(s[i-1]-'0')+s[i]-'0'<=26)) { flag[i]+=flag[i-2]; } } int res=flag[len-1]; delete []flag; return res; } };