题目描述
给定一个数字,按照如下规则翻译成字符串:0翻译成"a",1翻译成"b"…25翻译成"z"。一个数字有多种翻译可能,例如12258一共有5种,分别是bccfi,bwfi,bczi,mcfi,mzi。
实现一个函数,用来计算一个数字有多少种不同的翻译方法。
思路
动态规划,从最小的问题开始 :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
class Solution{
public:
int Get(int num){
if(num < 0)
return 0;
string str = to_string(num);
int res = GetCount(str);
return res;
}
private:
int GetCount(const string& str){
int n = str.length();
vector<int> counts(n+1, 0);
for(int i = n - 1; i >= 0; --i){
if(i == n - 1)
counts[i] = 1;
else
counts[i] = counts[i+1] + help(str, i, i+1) * (i == n-2 ? 1 : counts[i+2]);
}
return counts[0];
}
int help(const string& str, int i, int j){
int num1 = str[i] - '0';
int num2 = str[j] - '0';
int num = num1 * 10 + num2;
if(num <= 25 && num >= 10)
return 1;
else
return 0;
}
};