【问题标题】:how can i solve this problem of coins from n shop in python? [closed]我如何解决python中n商店的硬币问题? [关闭]
【发布时间】:2019-08-21 01:47:07
【问题描述】:

有一个问题,我们给了 n 家商店,每家商店都有 3 个硬币,即黄金,铂金,钻石
客户必须获得最大的硬币
条件如下
他最多只能从 1 家商店取 1 种硬币
例如

输入

我有一个矩阵
4 2 1 1 5 4 5 4 3 2 10 9 7 8 2 9

输出

答案是 27
因为我们从 1 和 3 商店拿金币,我们从商店 2 拿铂金币
我们从 4 号商店拿钻石币
所以商店 3 和商店 1=10+5
SHOP2=3
SHOP4=9
答案=10+5+3+9=27

【问题讨论】:

  • 那不就是所谓的背包问题(也称为背包问题)吗?
  • 我们如何将它与 KNAPSACK 联系起来,请您解释一下
  • 我不知道,输入似乎有点相似(有限的容量和各种的项目),所以我只是问(注意? 在我之前的评论结束时)

标签: python algorithm


【解决方案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

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

【讨论】:

  • 你能用背包的术语解释一下吗
  • 以前从未听说过
  • max_v, max_shop_idx = max((v[i], shop_idx) for shop_idx, v in enumerate(shops) if shop_idx in idx_remains) 你能解释一下这行吗
  • 我对此有意见。 which remain shop has max number of coin, and choose this one。 python语法问题可以google一下。
  • 这个解决方案在 idx_remains 变空时不起作用,在很多情况下也是如此。
猜你喜欢
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
  • 2016-10-25
  • 1970-01-01
  • 2020-09-04
  • 2019-11-16
  • 2022-01-16
  • 2021-12-10
相关资源
最近更新 更多