classSolution: defcrackNumber(self, ciphertext: int) -> int: ciphertext = str(ciphertext) n = len(ciphertext) dp = [0] * n dp[0] = 1 for i inrange(1, n): if10 <= int(ciphertext[i-1: i+1]) <= 25: if i == 1: dp[i] = 2 else: dp[i] = dp[i - 1] + dp[i - 2] else: dp[i] = dp[i - 1]
return dp[n - 1]
空间复杂度为O(n)
解法二-数字求余
优化空间复杂度可以从字符串的存储空间和动态规划数组入手
利用求余和求整运算,从右向左进行动态规划的计算,空间复杂度降至O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defcrackNumber(self, ciphertext: int) -> int: a = b = 1 y = ciphertext % 10 while ciphertext > 9: ciphertext //= 10 x = ciphertext % 10 temp = 10 * x + y if10 <= temp <= 25: c = a + b else: c = a a, b = c, a y = x return a