背包变化

时间:2018-07-09 07:59:17

标签: recursion dynamic-programming knapsack-problem

因此,我有一系列优惠券,每个优惠券都有价格和可以从中购买的商品数量。我只能从优惠券购买给定的商品数量,不能多也不能少。如何找到最低成本以获得带有优惠券的所需数量的商品(并尽可能返回-1)?

例如,如果有4张优惠券:“以10美元购买3个”,“以4美元购买2个”,“以4美元购买2个”和“以3美元购买1个”以及购买的4种商品,最低费用为8美元。

背包致力于寻找最大值,但对于最小值,它将继续不考虑任何优惠券,并给出0的答案。

这是我的代码:

int minimumCost(coupon_t coupons[], int numCoupons, int units) {

    if (units <= 0 || numCoupons <= 0)
        return 0;

    if (coupons[numCoupons-1].quantity > units)
        return minimumCost(coupons, numCoupons-1, units);

    coupon_t coupon = coupons[numCoupons-1];
    return min(coupon.price + minimumCost(coupons, numCoupons-1, units-coupon.quantity),
            minimumCost(coupons, numCoupons-1, units));

}

1 个答案:

答案 0 :(得分:1)

请多考虑一下。就像您说的那样,关键是处理0。在典型的背包代码中,0有两个含义:“不购买”和“不能购买”。拆分这些似乎可行:

def minimum_cost(coupons, units, coupon_no=0):
    if units < 0 or coupon_no == len(coupons):
        # special value for "impossible"
        return None

    if units == 0:
        # no more space, so we're not buying anything else
        return 0

    quantity, price = coupons[coupon_no]
    next_coupon = coupon_no + 1

    if quantity > units:
        return minimum_cost(coupons, units, next_coupon)

    pre_purchase_value_when_used = minimum_cost(coupons, units - quantity, next_coupon)
    value_when_unused = minimum_cost(coupons, units, next_coupon)

    # return whichever is not impossible, or cheaper of two possibilities:
    if pre_purchase_value_when_used is None:
        return value_when_unused
    elif value_when_unused is None:
        return pre_purchase_value_when_used + price
    else:
        return min(pre_purchase_value_when_used + price, value_when_unused)

coupons = [[3, 10], [2, 4], [2, 4], [1, 3]]
units = 4
cost = minimum_cost(coupons, units)
print(cost)
# => 8

(请注意,不是,除非您缓存函数结果,尽管使用表并不难。使用动态编程的关键见解是使用存储,以避免重新计算我们已经计算过的数据。)