解题思路:动态规划,(1)得到num的每一位数字,从低位到高位用nums保存(2)从低位到高位依次求解,状态转移方程如下:
d
p
[
i
]
=
{
d
p
[
i
−
1
]
+
d
p
[
i
−
2
]
10
≤
(
n
u
m
s
[
i
]
∗
10
+
n
u
m
s
[
i
−
1
)
<
26
d
p
[
i
−
1
]
o
t
h
e
r
s
dp[i]=\left\{ \begin{array}{lr} dp[i-1]+dp[i-2]&10\leq(nums[i]*10+nums[i-1)<26\\ dp[i-1] &others \end{array} \right.
dp[i]={dp[i−1]+dp[i−2]dp[i−1]10≤(nums[i]∗10+nums[i−1)<26others
dp[i]
表示低(i+1)位可以表示的字符串个数
代码如下:
class Solution:
def translateNum(self, num: int) -> int:
if num < 10:
return 1
nums = []
while(num):
nums.append(num % 10)
num //= 10
size = len(nums)
a1, a2 = 1, 1
for i in range(1,size):
if 10 <= (nums[i]*10 + nums[i-1]) < 26:
tmp = a1 + a2
else:
tmp = a1
a2 = a1
a1 = tmp
return a1