題目:
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.
分析:可以用貪心的思想,而且當前數字只與前面的數字有關。
代碼如下:
int numDecodings(string s) {
int n=s.size();
if(n==0)return 0;
int *result=new int[n+1];
memset(result,0,(n+1)*sizeof(int));
result[0]=1;
for(int i=1;i<=n;i++)
{
if(s[i-1]!='0')
{
result[i]+=result[i-1];
}
if(i>=2&&s[i-1]-'0'+10*(s[i-2]-'0')<=26&&s[i-1]-'0'+10*(s[i-2]-'0')>=10)
{
result[i]+=result[i-2];
}
}
return result[n];
}