【发布时间】:2020-05-26 16:51:33
【问题描述】:
我正在尝试解决如下动态规划问题,但无法解决。
给你一个原始计算器,它可以对当前数字 ???? 执行以下三个操作:乘 ????乘以 2,乘 ???? 3,或加 1 到????。你的目标是给定一个正整数???从数字 1 开始
我在 stackoverflow 本身上找到了解决方案,但无法理解发生了什么。
我听说每个 DP 问题都可以通过创建我试图做但不知道哪里出错的矩阵来解决。下面创建的表格显示了从 1 到达 n 所需的步骤数,最初我将值设为无穷大。
i / j 0 1 2 3 4 5
plus 1 0 1 2 3 4 5
multiple by 2 0 infinity 2 infinity 3 infinity
multiple by 3 0 infinity infinity 2 infinity infinity
我正在尝试用 Python 解决这个问题。 谁能帮帮我。
我找到了如下解决方案,但无法准确理解发生了什么:
import math
target = int(input())
def optVal(target, cache):
result = [1] * cache[-1] # 1
for i in range(1, cache[-1]): # 2
result[-i] = target # 3
if cache[target-1] == cache[target] - 1: # 4
target -= 1
elif target % 2 == 0 and (cache[target // 2] == cache[target] - 1): # 5
target //= 2
else: # 6 # target % 3 == 0 and (cache[target // 3] == cache[target] - 1):
target //= 3
return result
cache = [0] + [math.inf] * target # 1
for i in range(1, len(cache)): # 2
temp1 = math.inf
temp2 = math.inf
temp3 = math.inf
temp1 = cache[i - 1] + 1
if i % 2 == 0:
temp2 = cache[i // 2] + 1
if i % 3 == 0:
temp3 = cache[i // 3] + 1
cache[i] = min(temp1, temp2, temp3)
print('Minimum operation: ', cache[target] - 1)
finalLst = optVal(target, cache)
print(' '.join([str(x) for x in finalLst]))
Input:
5
Output:
3
1245
【问题讨论】:
-
问题陈述类似于编辑距离。结帐geeksforgeeks.org/edit-distance-dp-5
标签: python algorithm dynamic-programming