题目如下:
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.
分析如下:
首先题目典型的动态规划风格。用count[i]代表从string s的第0位到第i位的decode的方式, 用s(i, i+2)代表s的从i开始长度为2的sub string.
假设 count[i+2] = 0,而count [i+1], count[i], count[i-1]...count[0]的值都已经算出来了,那么动态转换的方程式将是,
if s(i, i+2) is a valid 2-digit number, then count[i + 2] += count[ i ];
if s(i, i+1) is a valid 2-digit number, then count[i + 2] += count[i + 1];
其中的base case是,计算count[0]和count[1]。
count[0]最多可以有1种decode方式。当s(0, 1)为[1, 9]中(不能包含0)的一个数时,才为1,否则为0,用代码中的辅助函数get_1_number()来计算。
count[1]最多可以有2种decode方式。第一种,仅当s(0,1)和s(1,2)都是一个[1, 9]的数时,第二种,当s(0,2)是一个[10, 26]的数时。
我的代码:
// 12ms class Solution { public: int get_1_number(string & s, int index) { int result = s[index] - '0'; return (result <= 9 && result >= 1) ? result : -1; } int get_2_number(string & s,int index) { int result = (s[index] - '0') * 10 + s[index + 1] - '0'; return (result <= 26 && result >= 10) ? result : -1; } int numDecodings(string s) { if (s.length() == 0 ) return 0; int * count = new int[s.length()]; memset(count, 0, sizeof(int) * s.length()); if (s.length() >= 1 && get_1_number(s, 0) != -1) count[0] = 1; if (count[0] == 1 && s.length() >= 2 && get_1_number(s, 1) != -1) count[1] = count[0]; if (s.length() >= 2 && get_2_number(s, 0) != -1) count[1] ++; for (int i = 2; i < s.length(); ++i) { if (count[i-1] != 0 && get_1_number(s, i) != -1) count[i] = count[i-1]; else count[i] = 0; if (count[i-2] != 0 && get_2_number(s, i - 1) != -1) count[i] += count[i-2]; } int result = count[s.length() - 1]; delete [] count; return result; } };