我们可以选择商店最大的硬币。所以关键是挑选的顺序。我认为您可以使用dfs 搜索所有的拣货订单,并找到最好的:
def pick_coins(demand, shops):
# invalid input
if sum(demand) > len(shops):
return -1
res = 0
def dfs(demand, idx_remains, num):
nonlocal res
# all picked up
if all(d == 0 for d in demand):
# record it if it is max so far
res = max(res, num)
return
for i, coin_num in enumerate(demand):
if coin_num > 0:
# which remain shop has max number of coin, and choose this one
max_v, max_shop_idx = max((v[i], shop_idx) for shop_idx, v in enumerate(shops) if shop_idx in idx_remains)
idx_remains.remove(max_shop_idx)
demand[i] -= 1
# do it recursively
dfs(demand, idx_remains, num + max_v)
# remember to revert the state when backtrack
idx_remains.append(max_shop_idx)
demand[i] += 1
dfs(demand, list(range(len(shops))), 0)
return res
def test():
demand = [2, 1, 1]
shops = [[5, 4, 5], [4, 3, 2], [10, 9, 7], [8, 2, 9]]
print(pick_coins(demand, shops)) # output 27
希望对您有所帮助,如果您还有其他问题,请发表评论。 :)