leetcode 638. 大礼包

题解

迭代,如果某个礼包special[i]是可以合法购买的(礼包物品的数量小于预购物品数),则以该礼包的价格special[i][len(needs)]加上购买剩余商品的最低价格,即对remainNeeds进行迭代

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func shoppingOffers(price []int, special [][]int, needs []int) int {
minPrice := 0
for i := 0; i < len(price); i++ {
minPrice += price[i] * needs[i]
}
for i := 0; i < len(special); i++ {
isValid := true
remainNeeds := make([]int, len(needs))
for j := 0; j < len(needs); j++ {
if special[i][j] > needs[j] {
isValid = false
break
}
remainNeeds[j] = needs[j] - special[i][j]
}
if isValid {
price := shoppingOffers(price, special, remainNeeds) + special[i][len(needs)]
if price < minPrice {
minPrice = price
}
}
}
return minPrice
}