题目:给定一个数字,我们按照如下规则把它翻译为字符串:0翻译成“a”,1翻译成“b”,·······,25翻译成“z”。一个数字可能有多个翻译。例如,12258有5种不同的翻译,分别是“bccfi”、"bwfi"、"bczi"、"mcfi"和"mzi"。请编程实现一个函数,用来计算一个数字有多少种不同的翻译方法。
思想:
本题可以用自上而下(即从前往后递归的方式),将12258分为1, 2258和12,258的方式然后分别算出两种情况下的种类数
但在计算1,2258时,我们会发现,2258可以分为2,258和22,58其中与12,258中的情况有重复,为了避免重复,可以从后往前计算(即自下而上),有点像动态规划的思想。
#include <iostream>
#include <string>
using namespace std;
int GetTranslationCount(int num);
int GetTranslationCount(const string& num);
int main()
{
int num = 0;
while(num != -1)
{
cout << "input a number "<<endl;
cin >> num;
int result = GetTranslationCount(num);
cout << "result: " << result << endl;
}
return 0;
}
int GetTranslationCount(int num)
{
if(num < 0)
return -1;
string strNum = to_string(num);
int result = GetTranslationCount(strNum);
return result;
}
int GetTranslationCount(const string& num)
{
int length = num.size();
int* counts = new int[length];
int count = 0;
for(int i = length - 1; i >= 0; --i)
{
if(i < length - 1)
count = counts[i+1];
else
count = 1;
if(i < length - 1)
{
int digit1 = num[i] - '0';
int digit2 = num[i+1] - '0';
int twoNum = digit1 * 10 + digit2;
if(twoNum <= 25 && twoNum >= 10)
{
if(i < length - 2)
count += counts[i+2];
else
count += 1;
}
}
counts[i] = count;
}
count = counts[0];
delete[] counts;
return count;
}