Created
March 17, 2013 05:54
-
-
Save zhoutuo/5180328 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int numDecodings(string s) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
if(s.length() == 0) { | |
return 0; | |
} | |
vector<int> res(s.length()); | |
for(int i = 0; i < res.size(); ++i) { | |
res[i] = -1; | |
} | |
calc(s, res); | |
return res[0]; | |
} | |
int calc(string s, vector<int>& res) { | |
if(s.length() == 0) { | |
return 1; | |
} | |
int cur = res.size() - s.length(); | |
if(res[cur] != -1) { | |
return res[cur]; | |
} | |
if(s[0] == '0') { | |
res[cur] = 0; | |
return res[cur]; | |
} | |
if(s.length() == 1) { | |
res[cur] = 1; | |
return res[cur]; | |
} | |
res[cur] = 0; | |
if(s[0] == '1' or ((s[0] == '2') and (s[1] - '0' <= 6))) { | |
res[cur] = calc(s.substr(2), res); | |
} | |
res[cur] += calc(s.substr(1), res); | |
return res[cur]; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment