这是Python中的一个快速解决方案:
def add50(passengers, buses):
proposed = buses + [50]
if sum(proposed) < passengers:
return add50(passengers, proposed)
return proposed
def add30(passengers, buses):
proposed = buses + [30]
if sum(proposed) < passengers:
proposed30 = add30(passengers, proposed)
proposed50 = add50(passengers, proposed)
return proposed30 if sum(proposed30) < sum(proposed50) else proposed50
return proposed
print add30(88, [])
print add30(75, [])
print add30(105, [])
当我运行它时,我得到:
[30, 30, 30]
[30, 50]
[30, 30, 50]
该代码在可能的情况下进行了深度优先搜索。由于顺序无关紧要([30, 50]
与相同[50, 30]
),我们可以通过仅添加相同大小或更大的总线来使搜索空间小得多。这就是为什么add30()
可以致电add50()
,而不是相反的原因。