剑指46:把数字翻译成字符串——类似回溯法


题目:给定一个数字,我们按照如下规则把它翻译为字符串:0翻译成"a",1翻译成"b",……,11翻译成"l",……,25翻译成"z"。一个数字可能有多个翻译。例如12258有5种不同的翻译,它们分别是"bccfi"、"bwfi"、"bczi"、"mcfi"和"mzi"。请编程实现一个函数用来计算一个数字有多少种不同的翻译方法。

思路:用递归的思想从上到下 用回溯法的思想从下到上去实现

对于一个数字 转字符串后  XXXXXXX  其从左到右下标分别为0~len-1,

即对于该范围内的i,定义一个f(i)表示在第i个位置时 有多少种  f(i)=f(i+1)+g(i,i+1)*f(i+2);其中 g代表0或1 当组成一个在10和25之间的数时即为1,用一个数组记录从一个字符串最右侧开始的种数,从右到左完成回溯

#include <string>
#include <iostream>

using namespace std;

int GetTranslationCount(const string& number);

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

int GetTranslationCount(const string& number)
{
    int len = number.size();
    int * res = new int[len];
    for(int i=len-1;i>=0;i--){
        if(i==len-1)
            res[i]=1;
        else
        {
            res[i]=res[i+1];
            int val = 10*(number[i]-'0')+number[i+1]-'0';
            if(val>=10&&val<=25)
            {
                if(i==len-2)
                    res[i] += 1;
                else
                    res[i] += res[i+2];
            }
        }
    }
    int result = res[0];
    delete []res;
    return result;
}


猜你喜欢

转载自blog.csdn.net/yanbao4070/article/details/80185765