Shopping Offers

本文针对LeetCode638题目的购物优惠算法进行深入解析,介绍了一种通过深度优先搜索结合动态规划的方法来求解最低价格的问题。算法使用了剪枝技巧来优化搜索过程,并详细展示了如何利用特殊优惠实现最优购买策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode 638 Shopping Offers


In LeetCode Store, there are some kinds of items to sell. Each item has a price.

However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.

You are given the each item’s price, a set of special offers, and the number we need to buy for each item. The job is to output the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers.

Each special offer is represented in the form of an array, the last number represents the price you need to pay for this special offer, other numbers represents how many specific items you could get if you buy this offer.

You could use any of special offers as many times as you want.


 public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        Map<List<Integer>, Integer> dp = new HashMap<>();
        List<Integer> allZero = new ArrayList<>();
        for (int i = 0; i < needs.size(); i++) {
            allZero.add(0);
        }
        dp.put(allZero, 0);
        return dfs(needs, price, special, dp);
    }

    private int dfs(List<Integer> needs, List<Integer> price, List<List<Integer>> special, Map<List<Integer>, Integer> dp) {
        if (dp.containsKey(needs))
            return dp.get(needs);
        int res = Integer.MAX_VALUE;
        for (List<Integer> s : special) {
            List<Integer> needsCopy = new ArrayList<>(needs);
            boolean valid = true;
            for (int i = 0; i < needs.size(); i++) {
                needsCopy.set(i, needsCopy.get(i) - s.get(i));
                // 剪枝
                if (needsCopy.get(i) < 0) {
                    valid = false;
                    break;
                }
            }
            if (valid) {
                res = Math.min(res, s.get(needs.size()) + dfs(needsCopy, price, special, dp));
            }
        }
        int noSpecial = 0;
        for (int i = 0; i < needs.size(); i++) {
            noSpecial += needs.get(i) * price.get(i);
        }
        res = Math.min(res, noSpecial);
        dp.put(needs, res);
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值