Decode Ways(C++解码方法)
(1)递归,超时
class Solution {
public:
int helper(string &s,int l) {
if(l==s.length()-1 && s[l]!='0') return 1;
else if(l==s.length()-1) return 0;
if(l>=s.length()) return 1;
string str="";
int temp,sum=0;
for(int i=l;i<s.length();i++) {
str.push_back(s[i]);
temp=stoi(str);
if(temp==0) return sum;
else if(temp<=26) sum+=helper(s,i+1);
else return sum;
}
return sum;
}
int numDecodings(string s) {
return helper(s,0);
}
};
(2)动态规划
class Solution {
public:
int numDecodings(string s) {
int m=s.length();
vector<int> v(m+1,0);
v[0]=1;
for(int i=1;i<m+1;i++) {
if(i-2>=0 && s[i-2]!='0' && (10*(s[i-2]-'0')+(s[i-1]-'0'))<=26)
v[i]+=v[i-2];
if(s[i-1]!='0')
v[i]+=v[i-1];
}
return v[m];
}
};
还没有评论,来说两句吧...