【发布时间】:2020-05-06 18:44:52
【问题描述】:
我正在通过 OpenCourseWare (https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0002-introduction-to-computational-thinking-and-data-science-fall-2016/assignments/) 上的 MIT6.0002 工作,但我被问题集 1 的 B 部分难住了。这个问题是作为背包问题的一个版本提出的,说明如下:
[Aucks 发现了一群能下不同重量金蛋的鹅] 他们希望在旅途中尽量少带鸡蛋,因为他们没有太多空间 在他们的船上。他们详细记录了鹅可以产下的所有鸡蛋的重量 在给定的羊群中,他们的船可以承载多少重量。 实现一个动态规划算法来找到最少需要的鸡蛋数量 在 dp_make_weight 中为某艘船设定一个给定的重量。结果应该是一个整数 表示从给定的鹅群中生产所需的最小鸡蛋数量 给定重量。您的算法不需要返回鸡蛋的重量,只需返回 最少的鸡蛋数量。 假设: - 不同鹅之间的所有鸡蛋重量都是唯一的,但给定的鹅总是会产下相同大小的鸡蛋 - Aucks 可以等待鹅产下所需数量的蛋[即每种尺寸的蛋都有无限供应]。 - 总有可用的 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()
【问题讨论】:
标签: python recursion dynamic-programming