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.
思路:
這也是一個典型的DP問題,首先定義一個數組,dp[i]為到第i個字符所能組成的所有編碼方式的個數。那麼對於dp[i+1]來說,肯定至少和dp[i]一樣多,如果第i個字符和i+1個字可以合成一個字符,那麼dp[i+1] += dp[i-1]。不過這裡需要注意的是違規字符。
#include#include #include using namespace std; int Decode_num(string& str) { vector vec(str.size(),0); if(str.size() <2) return 1; vec[0] =1; if(str[0]=='1' || str[1]<='6') vec[1] =2; int i; int tmp; for(i=2;i