0 -> 'a', 1->'b', ..., 11 -> 'l', ..., 25->'z'. 计算一个数有多少种不同的翻译方法。

分析:记f[i]表示从第i位起的不同翻译数目。

f[i] = f[i + 1] + g(i, i + 1) * f[i + 2]. g(i, i + 1)拼起来的数字如果在10-25之间,则为1,否则为0.

 1 int GetTranslationCount(int number) {
 2     if (number < 0) {
 3         return 0;
 4     }
 5     string numberInstring = to_string(number);
 6     return GetTranslationCount(numberInstring);
 7 }
 8 
 9 int GetTranslationCount(const string& number) {
10     int len = number.length();
11     int *count = new int[length];
12     int count = 0;
13     for (int i = len - 1; i >= 0; i--) {
14         count = 0;
15         if (i < len - 1) {
16             count = counts[i + 1];
17         } else {
18             count = 1;
19         }
20         if (i < len - 1) {
21             int digit1 = numbers[i] - '0';
22             int digit2 = numbers[i + 1] - '0';
23             int converted = digit1 * 10 + digit2;
24             if (converted >= 10 && converted <= 25) {
25                 if (i < len - 2) {
26                     count += counts[i + 2];
27                 } else {
28                     count += 1;
29                 }
30             }
31         }
32         counts[i] = count;
33     }
34     count = counts[0];
35     delete[] counts;
36     return count;
37 }

 

相关文章:

  • 2022-01-01
  • 2022-01-04
  • 2021-12-12
  • 2022-03-08
  • 2021-09-23
  • 2022-02-04
  • 2022-12-23
猜你喜欢
  • 2021-06-06
  • 2021-10-30
  • 2021-12-31
  • 2021-12-02
  • 2021-06-12
  • 2021-05-19
相关资源
相似解决方案