# 递归解法
class Solution:
def translateNum(self, num: int) -> int:
def trans(num):
if len(num) <= 1:
return 1
count = 0
count += trans(num[1:])
if num[0] != "0" and int(num[:2]) < 26:
count += trans(num[2:])
return count
return trans(str(num))
# 二分
class Solution:
def translateNum(self, num: int) -> int:
num = str(num)
def trans(begin, end):
if end - begin <= 0:
return 1
mid = begin + (end - begin) // 2
flag = 0
p = trans(begin, mid)
q = trans(mid + 1, end)
if 1 <= int(num[mid]) <= 2 and int(num[mid:mid + 2]) < 26:
flag = trans(begin, mid - 1) * trans(mid + 2, end)
return p * q + flag
return trans(0, len(num) - 1)
# 动态规划
class Solution:
def translateNum(self, num: int) -> int:
num = str(num)
n = len(num)
if n <= 1:
return 1
dp = [1, 1]
i = 1
while i < n:
if num[i - 1] == '1' or (num[i - 1] == '2' and num[i] in "012345"):
tmp = dp[0] + dp[1]
else:
tmp = dp[1]
dp[0] = dp[1]
dp[1] = tmp
i += 1
return dp[-1]
# TODO: 减少时间复杂度
每日一练7.12——将数字转换为字符串
最新推荐文章于 2022-07-12 20:06:49 发布