剑指offer 把数字转换成字符串(动态规划)

题目:给定一个数字,我们按照如下规则把它翻译为字符串: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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值