我尝试为到达n和随后的列表的最小所需步骤正确编写代码,将步骤乘以2或3或加1。由于对此使用了贪婪的选择,因此应该通过动态编程来实现是不安全的。首先,我使用以下代码获得了最低限度的步骤,它可以正常工作。 我无法获得的是如何解压缩该列表,请不要提供答案,这是在线课程的作业,提示或“帮助还可以”,所以我在这里尝试保持我的道德正直。 / p>
def optimal_sequence(n):
sequence = [0]*(n+1)
for i in range(2, n+1):
if i % 3 == 0:
sequence[i] = sequence[(i // 3)]+1
if sequence[i] - sequence[i-1] <= 1:
sequence[i] = sequence[i]
else:
sequence[i] = sequence[i-1] + 1
elif i % 2 == 0:
sequence[i] = sequence[(i // 2)]+1
if sequence[i] - sequence[i-1] <= 1:
sequence[i] = sequence[i]
else:
sequence[i] = sequence[i-1] + 1
else:
sequence[i] = sequence[i-1] + 1
return sequence
while n >= 1:
seq.append(n)
if n % 3 == 0 and sequence[n] != sequence[n//3]: n = n // 3
elif n % 2 == 0 and sequence[n] != sequence[n//2]: n = n // 2
else: n = n-1
seq.reverse(); return seq
这里是如何映射最小数量的,例如n = 28,
n = 28
print(optimal_sequence(n))
>>> [0, 0, 1, 1, 2, 3, 2, 3, 3, 2, 3, 4, 3, 4, 4, 4, 4, 5, 3, 4, 4, 4, 5, 6, 4, 5, 5, 3, 4]
现在,如果您可以帮助我看看代码是否适合第一部分,如果正确,那么从while开始的第二部分有什么问题。 谢谢