我是一名有用的助手,可以为您翻译文本。
这个问题要求解决方案必须使用动态规划。我写了一个解决方案(用Python),我认为它可以找到最优解,但它没有使用动态规划,我也不明白如何应用动态规划。还有建议说解决方案应该使用递归。
有人能向我解释一下在这种情况下使用记忆化的优势是什么,以及如果我实现一个递归解决方案,我将获得什么好处? (如果我的问题太模糊或者解决方案对于初学编程和这个网站的人来说太明显,那我很抱歉)。
我的代码:
我正在通过MIT6.0002开放式课程学习(https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0002-introduction-to-computational-thinking-and-data-science-fall-2016/assignments/),我在第一组问题集的B部分遇到了难题。这个问题被描述为背包问题的一个版本,其陈述如下:
[奥克斯发现了一群鹅,它们产下各种重量的金蛋] 他们希望在航行时尽可能少地携带金蛋,因为他们的船只空间有限。他们已经详细记录了鹅群中所有蛋的重量以及他们的船只可以承受多少重量。 实现一个动态规划算法,在 dp_make_weight 中找到制造给定重量所需的最少鸡蛋数。结果应该是一个整数,代表从给定的鹅群中制造给定重量所需的最少鸡蛋数。你的算法不需要返回鸡蛋的重量,只需要返回最少的鸡蛋数量。 假设: - 不同鹅之间的所有蛋的重量都是唯一的,但是同一只鹅总是会产下相同大小的蛋 - 奥克斯可以等待鹅产出他们需要的任意数量的蛋[即每种大小的蛋都有无限供应] - 总是有大小为1的蛋可用这个问题要求解决方案必须使用动态规划。我写了一个解决方案(用Python),我认为它可以找到最优解,但它没有使用动态规划,我也不明白如何应用动态规划。还有建议说解决方案应该使用递归。
有人能向我解释一下在这种情况下使用记忆化的优势是什么,以及如果我实现一个递归解决方案,我将获得什么好处? (如果我的问题太模糊或者解决方案对于初学编程和这个网站的人来说太明显,那我很抱歉)。
我的代码:
#================================
# Part B: Golden Eggs
#================================
# Problem 1
def dp_make_weight(egg_weights, target_weight, memo = {}):
"""
Find number of eggs to bring back, using the smallest number of eggs. Assumes there is
an infinite supply of eggs of each weight, and there is always a egg of value 1.
Parameters:
egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk)
target_weight - int, amount of weight we want to find eggs to fit
memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation)
Returns: int, smallest number of eggs needed to make target weight
"""
egg_weights = sorted(egg_weights, reverse=True)
eggs = 0
while target_weight != 0:
while egg_weights[0] <= target_weight:
target_weight -= egg_weights[0]
eggs += 1
del egg_weights[0]
return eggs
# EXAMPLE TESTING CODE, feel free to add more if you'd like
if __name__ == '__main__':
egg_weights = (1, 5, 10, 25)
n = 99
print("Egg weights = (1, 5, 10, 25)")
print("n = 99")
print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)")
print("Actual output:", dp_make_weight(egg_weights, n))
print()