我该如何解决python中来自n店的硬币问题?

时间:2019-03-30 06:48:42

标签: python algorithm

有一个问题,我们给n个商店,每个商店有3个硬币,即GOLD,PLATINUM,DIAMOND
客户必须获得最多的硬币
条件如下
他最多只能从1家商店拿走1种硬币
例如

输入

我有一个矩阵
4 <---没有商店
2 1 1 <-最大数量的黄金,铂金,钻石
5 4 5 <-商店1拥有5金币,4铂金和5钻石币
4 3 2 <-用于商店2
10 9 7 <-适用于商店3
8 2 9 <-用于商店4

输出

答案是27
我们从1号和3号店取金币,而2号店取铂金币
从4号店拿钻石硬币
所以SHOP 3 AND SHOP1 = 10 + 5
SHOP2 = 3
SHOP4 = 9
answer = 10 + 5 + 3 + 9 = 27

1 个答案:

答案 0 :(得分:-1)

我们可以选择商店最多的硬币。因此,关键是拣选顺序。我认为您可以使用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

希望对您有所帮助,如有其他问题,请发表评论。 :)