【剑指offer】46、把数字翻译成字符串

题目

给定一个数字,按照如下规则翻译成字符串:

0->a

1->b

...

25->z

因此一个数字可能有多种翻译。例如,12258有5种不同的翻译,bccfi,bwfi,bczi,mcfi,mzi。

请实现一个函数,计算数字有多少种翻译方法。

思路

可以用递归解决,会发现子问题258 58都重复了。

自然想到可以用动态规划来解决,用f(i)来表示从第i位数字开始不同的翻译数目,

我们可以写出转移矩阵

g(i,i+1)表示第i位和i+1位拼起来的数字在10~25范围内,值为1,否则为0。

先f(5) = 1, f(4) = 1

f(3) = f(4) + 0 = 1

f(2) = f(3) + f(4) = 2

f(1) = f(2) + f(3) = 3

f(0) = f(1) + f(2) = 5 

int GetTranslationCount(int number){
    if (number < 0)
        return 0;
    string numberString = to_string(number);
    return GetTranslationCount(numberString);
}

int GetTranslationCount(const string& number){
    int length = number.length();
    int* f = new int[length];
    int count = 0;

    for (int i = length - 1; i >= 0; i++){
        count = 0;
        i < length - 1 ? count = f[i + 1] : 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){
                i < length - 2 ? count += f[i + 2] : count += 1;
            }
        }
        f[i] = count;
    }
    count = f[0];
    delete[] f;

    return count;
}

猜你喜欢

转载自www.cnblogs.com/shiganquan/p/9347102.html