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 等需要跑几遍试出来,造成我的WA特别多
没有出现中断条件时
dp[i][0] = dp[i-1][0]+dp[i-1][j]
dp[i][1] = dp[i][0]
出现中断条件时 s[i] > '2' || s[i-1]<='2'&&s[i] >'6'
分块然后把每块的可能性相乘。
int dp[1000][2]={0};
int numDecodings(char* s) {
int index;
if(s[0]=='\0'||s[0]=='0') return 0;
// dp[1][0]=(s[0]>'0')&&(s[0]<='9')?1:0;
dp[0][0]=1;
dp[0][1]=0;
// dp[1][1]=(s[0]-'2')>0?0:1;
int carry=0;
int i =0;
int sum =1;
int error=0;
for (index=1;s[i]!='\0'; index++) {
if(s[i-1]=='2'&&((s[i]-'6')>0))
{
sum*=dp[index-1][0];
dp[index][0]=1;
dp[index][1]=0;
if (s[i+1]=='0') {
return 0;
}
}
else if ((s[i]-'2')>0)
{
sum*=(dp[index-1][0]+dp[index-1][1]);
dp[index][0]=1;
dp[index][1]=0;
if (s[i+1]=='0') {
return 0;
}
}
else if(s[i]=='0')
{
// sum*=(dp[index-1][0]);
dp[index][0]=dp[index-2][0];
dp[index][1]=dp[index-2][1];
if(s[i+1]=='0')
{
return 0;
}
}
else
{
error=0;
carry =dp[index-1][1];
dp[index][0] = dp[index-1][0]+carry;
dp[index][1] = (s[i]-'2')>0?0:dp[index-1][0];
//sum*=dp[index][0];
}
if(error>=2)
{
return 0;
}
i++;
}
sum*=dp[index-1][0];
return sum;
}