题目:
给定一个数字,我们按照如下规则把它翻译为字符串:0翻译成“a”,1翻译成“b”,……,11翻译成“1”,……,25翻译成“z”。一个数字可能有多个翻译。例如:12258有5种不同的翻译,分别是“bccfi”、“bwfi”、“bczi”、“mcfi”和“mzi”。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。
链接:
剑指Offer(第2版):P231
思路标签:
- 算法:递归、动态规划
解答:
用递归自顶向下分析,用动态规划自低向上求解
- 定义问题:当最开始的一个或者两个数字被翻译成一个字符后,我们接着翻译后面剩下的数字;
- 用一个递归式来表示:定义f(i)表示从第i位数字开始的不同翻译的数目,那么f(i) = f(i+1) + g(i,i+1)*f(i+2);当第i位和第i+1位两位数字拼接起来的数字在10~25的范围内时,函数g(i,i+1)的值为1,否则为0。
- 该问题使用上面的递归方法会存在很多重复子问题。所以我们使用动态规划的方法,自低向上求解问题,消除重复子问题。
class Solution {
public:
int GetTranslationCount(int number) {
if (number < 0)
return 0;
string numberInString = to_string(number);
return GetTranslationCount(numberInString);
}
int GetTranslationCount(const string& number) {
int length = number.length();
int* counts = new int[length];
int count = 0;
for (int i = length - 1; i >= 0; i--) {
count = 0;
if (i < length - 1)
count = counts[i + 1];
else
count = 1;
if (i < length - 1) {
int digit1 = number[i] - '0';
int digit2 = number[i + 1] - '0';
int converted = digit1 * 10 + digit2;
if (converted >= 10 && converted <= 25) {
if (i < length - 2)
count += counts[i + 2];
else
count += 1;
}
}
counts[i] = count;
}
count = counts[0];
delete[] counts;
return count;
}
};
C++相关
- C++11
std::to_string