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.
思路:
1.和 restore ip address 题意几乎一致, 不过这道题不要打印路径, 所以, dp 更适合。用前者dfs的方法会导致超市。
2 用动态规划的思路,找到转移函数
Count[i] = Count[i-1] if S[i-1] is a valid char
or = Count[i-1]+ Count[i-2] if S[i-1] and S[i-2] together is still a valid char.
int check(char one){
return (one != '0') ? 1:0;
}
int check(char one, char two){
return (one =='1' || (one=='2'&& two<='6'))?1:0;
}
int numDecodings(string s){
if(s.size()<=0 || s[0]=='0') return 0;
if(s.size()==1 && s[0]!='0') return 1;
vector<int> dp(s.size(),0);
dp[0] = check(s[0]);
dp[1] = (check(s[0])*check(s[1]))+check(s[0],s[1]);
for(int i=2; i<s.size(); i++){
if(check(s[i])){
dp[i] += dp[i-1];
}
if(check(s[i-1],s[i])){
dp[i] += dp[i-2];
}
}
return dp[s.size()-1];
}