每日随机一题 leetcode638. 大礼包

题:


思:深搜暴力解法


码:

public static int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        // 深搜 要使得needs的所有元素恰好变为0时,所需的最小的价格和
        // 对于needs的每一项,只要不为0,就有以下几种选择:
        // 1.直接减少自己 2.寻找一个包含自己的礼包,对于每一种情况,分别 探讨是否可以购买本礼包,如果可以,则购买
        // 如果needs这一项为0,则考虑下一项
        // 递归结束条件,当递归到needs的最后一项时,递归结束,更新最小的价格和
        int minSum[] = new int[1];
        minSum[0] = Integer.MAX_VALUE;
        dfs(price, special, needs, 0, minSum, 0);
        return minSum[0];
    }

    public static void dfs(List<Integer> price, List<List<Integer>> special, List<Integer> needs, int curPriceSum, int[] minSum, int curIndex) {
        // 递归结束条件
        if (curIndex == needs.size()) {
            minSum[0] = Math.min(curPriceSum, minSum[0]);
            return;
        }

        if (needs.get(curIndex) > 0) {
            // 单买,买完以后记得加回来
            needs.set(curIndex, needs.get(curIndex) - 1);
            dfs(price, special, needs, curPriceSum + price.get(curIndex), minSum, curIndex);
            needs.set(curIndex, needs.get(curIndex) + 1);
            // 通过大礼包购买,考虑所有大礼包的情况
            for (int i = 0; i < special.size(); i++) {
                List<Integer> libao = special.get(i);
                int k = 0;
                for (; k < libao.size() - 1; k++) {
                    if (libao.get(k) > needs.get(k)) {
                        break;
                    }
                }
                if (k < libao.size() - 1)
                    continue;
                else {
                    // 可以买这个礼包
                    for (int l = 0; l < libao.size() - 1; l++) {
                        needs.set(l, needs.get(l) - libao.get(l));
                    }
                    dfs(price, special, needs, curPriceSum + libao.get(libao.size() - 1), minSum, curIndex);
                    for (int l = 0; l < libao.size() - 1; l++) {
                        needs.set(l, needs.get(l) + libao.get(l));
                    }
                }
            }
        } else {
            dfs(price, special, needs, curPriceSum, minSum, curIndex + 1);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值