638. 大礼包

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

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shopping-offers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.List;

class Solution {

    private int ans = Integer.MAX_VALUE;

    private void solve(List<Integer> price, List<List<Integer>> special, int index, List<Integer> needs, int sum) {

        if (index == special.size()) {
            for (int i = 0; i < price.size(); ++i) {
                sum += price.get(i) * needs.get(i);
            }
            ans = Math.min(ans, sum);
            return;
        }
        /**
         * 不选
         */
        solve(price, special, index + 1, needs, sum);

        /**
         * 选
         */
        boolean canSelect = true;
        for (int i = 0; i < needs.size(); ++i) {
            if (special.get(index).get(i) > needs.get(i)) {
                canSelect = false;
                break;
            }
        }

        if (canSelect) {
            int cost = 0;
            for (int i = 0; i < price.size(); ++i) {
                cost += price.get(i) * needs.get(i);
            }
            if (cost > special.get(index).get(needs.size())) {
                for (int i = 0; i < needs.size(); ++i) {
                    needs.set(i, needs.get(i) - special.get(index).get(i));
                }
                solve(price, special, index, needs, sum + special.get(index).get(needs.size()));
                for (int i = 0; i < needs.size(); ++i) {
                    needs.set(i, needs.get(i) + special.get(index).get(i));
                }
            }
        }
    }

    public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        solve(price, special, 0, needs, 0);
        return ans;
    }
}
posted @ 2022-02-18 16:40  Tianyiya  阅读(60)  评论(0)    收藏  举报