力扣: 638. 大礼包

该博客介绍了一个使用动态规划解决购物优惠问题的算法。通过过滤无效的优惠组合,优化了计算过程,最终找到购买商品的最低价格。算法中利用了HashMap进行记忆化搜索,减少了重复计算。
class Solution {
    Map<List<Integer>, Integer> memo = new HashMap<>();
    public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        int n = price.size();

        // 过滤掉不需要计算的大礼包,只保留需要计算的大礼包
        List<List<Integer>> filterSpecial = new ArrayList<>();
        for (List<Integer> sp : special){
            int totalCount = 0, totalPrice = 0;
            // 计算大礼包的价格
            for (int i = 0; i < n; i++){
                totalCount += sp.get(i);
                // 计算这个物品的价格
                totalPrice += sp.get(i) * price.get(i);
            }
            if (totalCount > 0 && totalPrice > sp.get(n)){
                filterSpecial.add(sp);
            }
        }
        return dfs(price, special, needs, filterSpecial, n);
    }

    private int dfs(List<Integer> price, List<List<Integer>> special, List<Integer> needs, List<List<Integer>> filterSpecial, int n ){
        if (!memo.containsKey(needs)){
            int minPrice = 0;
            for (int i = 0; i < n; i++){
                minPrice += needs.get(i) * price.get(i);
            }
            for (List<Integer> curSpecial : filterSpecial){
                int specialPrice = curSpecial.get(n);
                List<Integer> nextNeeds = new ArrayList<>();
                for (int i = 0; i < n; i++){
                    if (curSpecial.get(i) > needs.get(i) ){
                        break;
                    }
                    nextNeeds.add(needs.get(i) - curSpecial.get(i));
                }
                if (nextNeeds.size() == n){
                    minPrice = Math.min(minPrice, dfs(price, special, nextNeeds, filterSpecial, n) + specialPrice);
                }
            }
            memo.put(needs, minPrice);
           
        }
        return memo.get(needs);
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值