638.大礼包

118 阅读2分钟

题目:
在 LeetCode 商店中, 有 n 件在售的物品。每件物品都有对应的价格。然而,也有一些大礼包,每个大礼包以优惠的价格捆绑销售一组物品。

给你一个整数数组 price 表示物品价格,其中 price[i] 是第 i 件物品的价格。另有一个整数数组 needs 表示购物清单,其中 needs[i] 是需要购买第 i 件物品的数量。

还有一个数组 special 表示大礼包,special[i] 的长度为 n + 1 ,其中 special[i][j] 表示第 i 个大礼包中内含第 j 件物品的数量,且 special[i][n] (也就是数组中的最后一个整数)为第 i 个大礼包的价格。

返回 确切 满足购物清单所需花费的最低价格,你可以充分利用大礼包的优惠活动。你不能购买超出购物清单指定数量的物品,即使那样会降低整体价格。任意大礼包可无限次购买。
算法:

dp[needs]定位为需求物品为needs的最低花费(needs数组通过某种方法转化为一个key)。要买齐商品needs,可以按prices原价买齐,花费cost_price,也可以从大礼包中购买选择任意一个购买,假设选择第i个花费cost_special_i,则cost_special_i = special[n] + dp[needs - special[:n]]。
所以最小的花费为:min(cost_price, cost_special_0,cost_special_1...cost_special_i )

方法一:记忆化搜索

func shoppingOffers(price []int, special [][]int, needs []int) int {
	n := len(price)
	cache := make(map[string]int)
	var dfs func(curNeeds []byte) int 
	dfs = func(curNeeds []byte) int {
		if cost, ok := cache[string(curNeeds)]; ok {
			return cost
		}
		// 原价购买的花费
		cost := 0
		for i := range curNeeds {
			cost = cost + price[i] * int(curNeeds[i])
		}
		// 选择一个大礼包购买的花费
		nextNeeds := make([]byte, n)
		for j := range special {
			valid := true
			for k := 0; k < n; k ++ {
				if special[j][k] > int(curNeeds[k]) {
					valid = false
					break
				}
				nextNeeds[k] =  curNeeds[k] - byte(special[j][k])
			}
			if !valid {
				continue
			}
			cost = min(cost, dfs(nextNeeds) + special[j][n])
		}
		cache[string(curNeeds)] = cost
		return cost
	}
	newNeeds := make([]byte, len(needs))
	for i := range needs {
		newNeeds[i] = byte(needs[i])
	}
	return dfs(newNeeds)
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}