Leetcode638:大礼包

编程入门 行业动态 更新时间:2024-10-19 18:28:35

Leetcode638:<a href=https://www.elefans.com/category/jswz/34/1762751.html style=大礼包"/>

Leetcode638:大礼包

Leetcode638:大礼包

  • 题目:

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

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

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

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

  • 思路:回溯算法 dfs

  • 代码如下:

class Solution {private int res = Integer.MAX_VALUE;List<Integer> price;List<List<Integer>> special;public int shoppingOffers(List<Integer> _price, List<List<Integer>> _special, List<Integer> needs) {this.price = _price;this.special = _special;dfs(needs,0);return res;}void dfs(List<Integer> needs,int money){//尝试每一种大礼包,看看哪一种符合就用哪一种for(int i = 0; i < special.size(); i++){List<Integer> list = special.get(i);List<Integer> cur = new ArrayList<>();for(int j = 0; j < list.size(); j++){if(j== list.size()-1){dfs(cur,money + list.get(j));}else{int num = needs.get(j);if(num < list.get(j)) break;cur.add(num - list.get(j));}}}int m = money;//走到这里说明没有符合的大礼包了,直接减去每个的单价就行for(int i = 0; i < needs.size(); i++){m += price.get(i)*needs.get(i);}res =  Math.min(m,res);}
}

更多推荐

Leetcode638:大礼包

本文发布于:2024-02-24 15:29:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1695771.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:大礼包

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!