Description Submission Solutions Add to List
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.
class Solution { public: int numDecodings(string s) { if(s.empty()) return 0; int n = s.size(); vector<int> dp(n + 1, 0); dp[0] = 1; for(int i = 1; i <= n; i++){ dp[i] += s[i - 1] == ‘0‘ ? 0 : dp[i - 1]; if(i >= 2 && s.substr(i - 2, 2) >= "10" && s.substr(i - 2, 2) <= "26"){ dp[i] += dp[i - 2];//其实就是dp[i] = dp[i - 1] + dp[i - 2] 因为当是两位数时,有两种decode的方法 } } return dp[n]; } };
原文:http://www.cnblogs.com/93scarlett/p/6391455.html