剑指Offer(第二版)面试题46:把数字翻译成字符串
2018-01-08 11:22
483 查看
剑指Offer(第二版)面试题46:把数字翻译成字符串
题目要求:
给定一个数字,按照如下规则翻译成字符串:0翻译成“a”,1翻译成“b”…25翻译成“z”。一个数字有多种翻译可能,例如12258一共有5种,分别是bccfi,bwfi,bczi,mcfi,mzi。实现一个函数,用来计算一个数字有多少种不同的翻译方法。解题思路:
下面我们从自上而下和自下而上两种角度分析这道题目,以12258为例:自上而下,从最大的问题开始,递归 : 12258 / \ b+2258 m+258 / \ / \ bc+258 bw+58 mc+58 mz+8 / \ \ \ \ bcc+58 bcz+8 bwf+8 mcf+8 mzi / \ \ \ bccf+8 bczi bwfi mcfi / bccfi 有很多子问题被多次计算,比如258被翻译成几种这个子问题就被计算了两次。 自下而上,动态规划,从最小的问题开始 : f(r)表示以r为开始(r最小取0)到最右端所组成的数字能够翻译成字符串的种数。对于长度为n的数字,f(n)=0,f(n-1)=1,求f(0)。 递推公式为 f(r-2) = f(r-1)+g(r-2,r-1)*f(r); 其中,如果r-2,r-1能够翻译成字符,则g(r-2,r-1)=1,否则为0。 因此,对于12258: f(5) = 0 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 作者:ryderchan 链接:https://www.jianshu.com/p/80e1841909b7 來源:简书 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
C++代码
#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) 9ff9 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; }
参考文献
剑指offer第二版-46.把数字翻译成字符串(递归,动态规划)相关文章推荐
- 剑指Offer_46 把数字翻译成字符串
- 剑指Offer(第二版)面试题56:数组中数字出现的次数
- 剑指Offer(第二版)面试题53:在排序数组中查找数字出现的次数
- 面试题:把数字翻译成字符串
- 剑指Offer(第二版)面试题11:旋转数组的最小数字
- 剑指Offer(第二版)面试题44:数字序列中某一位的数字
- 剑指Offer-46:把数字翻译成字符串
- 剑指offer 面试题8:旋转数组的最小数字 题解
- 剑指offer-面试题38-数字在排序数组中出现的次数
- 剑指offer - 面试题51:数组中重复的数字
- 剑指Offer:面试题46 求1+2+...+n
- 面试题--两个字符串数字相加,不能用jdk自带的类型转换方法
- 剑指offer-面试题49-把字符串转换成整数
- 剑指Offer(第二版)面试题8:二叉树的下一个节点
- 《剑指offer面试题4》替换空格——实现函数把字符串中每个空格替换成“%20”
- (剑指Offer)面试题28:字符串的排列
- 剑指Offer系列-面试题42:翻转单词顺序和左旋转字符串
- 剑指offer--字符串转数字 string to int
- 剑指Offer(第二版)面试题47:礼物的最大价值
- 剑指offer面试题[49]-把字符串转化为整型