标签:
There are two ways to solve this problem. One is to solve it front-back, the other is back-front.
I currently only wrote the back-front method:
Suppose we have such a string: a0, a1, a2.... ai, ai+1, ai+2...an-1
Suppose we have get that from an-1, an-2...ai+2, the ways of decoding such a sequence is dp[i+2]
There are three conditions to consider:
1: if ai == 1, we dont need to care about ai+1, the ways to decode is 1+ dp[i+2];
2: if ai == 2, ai+1 should be smaller than ‘6‘, the ways to decode is 1 + dp[i+2].
3: if ai == 2, ai+1 greater than ‘6‘, the ways to decode is dp[i+1].
Think that, decode a individual number is 1, but 0 has no way to decode, thus, 0.
So, we can have the dynamic function: dp[i] = dp[i] + dp[i+2] if(s[i] == 1 || s[i] == 2 && s[i + 1] < ‘6‘)
#include <string> #include <vector> #include <iostream> using namespace std; /* 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" or "L". The number of ways decoding "12" is 2. */ /* Analyze: Several example will make this question clear. "102" --> "10", "2" -> total method is 1 "12" --> {"1", "2"}, "12" --> total method is 2. "127" --> {"1", "2", "7"}, {"12", "7"} --> total method is 2 "126" --> {"1", "2", "6"}, {"12", "6"}, {"1", "26"}--> total method is 3. There are several cases need special attentions. 1: "1"/"2" + "0", the char "0" can be interpreted as a decode way. 2: "2" + "7, 8, 9" can only be interpreted as one way. */ int numDecodings(string s) { int n = s.size(); vector<int> dp(n+2, 1); for(int i = s.size() - 1; i >= 0; --i) { if(s[i] == 0) dp[i] = 0; else dp[i] = dp[i + 1]; if(i + 1 < s.size() && (s[i] == '1' || (s[i] == '2' && s[i+1] <= '6'))) { dp[i] += dp[i+2]; } } return dp[0]; } int main(void) { cout << "123" << " decode ways: "<< numDecodings("123") << endl; cout << "102" << " decode ways: "<< numDecodings("102") << endl; cout << "127" << " decode ways: "<< numDecodings("127") << endl; }
标签:
原文地址:http://blog.csdn.net/github_34333284/article/details/51352223