題目:給定一個數字,我們按照如下規則把它翻譯爲字符串: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;
}