数组翻译成字符串有多少种方法-动态规划
题目:给定一个数字,我们按照如下规则把它翻译为字符串:0翻译成 “a”,1翻译成“b”,……,11翻译成“1”,……,25翻译成“z”。一个数 字可能有多个翻译。例如,12258有5种不同的翻译,分别是“ bcci”、“bwf” “bczi”、“mcf”和“mzi”。请编程实现一个函数,用来计算一个数字有多 少种不同的翻译方法
分析:数字最大到25,因此只有两种划分方式,建立F(i)和F(i-1)以及F(i-2)的递推关系即可
# give a num, 0 can be 'a', 1 can be 'b', ... 25 can be 'z'
# how many strings a num can be?
# use dp, first convert a num to string, then make F(i) present num[0-i] have how many ways
# F(i) = F(i-1), if num[i-1:i+1] <=25, then F(i)=F(i-1)+F(i-2)
def MyNum2Str(num):
myNum = str(num)
if len(myNum)==1:
return 1
dp = [-1 for xx in myNum]
dp[0] = 1
if myNum[0]!='0' and int(myNum[0:2])<=25:
dp[1] = 2
else:
dp[1] = 1
for i in range(2,len(myNum)):
if int(myNum[i-1:i+1])<=25 and myNum[i-1]!='0':
dp[i] = dp[i-1]+dp[i-2]
else:
dp[i] = dp[i-1]
print(dp)
return dp[-1]
print(MyNum2Str(12258))