LeetCode 大礼包(回溯法+剪枝)

在LeetCode商店中, 有许多在售的物品。

然而,也有一些大礼包,每个大礼包以优惠的价格捆绑销售一组物品。

现给定每个物品的价格,每个大礼包包含物品的清单,以及待购物品清单。请输出确切完成待购清单的最低花费。

每个大礼包的由一个数组中的一组数据描述,最后一个数字代表大礼包的价格,其他数字分别表示内含的其他种类物品的数量。

任意大礼包可无限次购买。

示例 1:

输入: [2,5], [[3,0,5],[1,2,10]], [3,2]
输出: 14
解释: 
有A和B两种物品,价格分别为¥2和¥5。
大礼包1,[3,0,5]你可以以¥5的价格购买3A和0B。
大礼包2, [1,2,10]你可以以¥10的价格购买1A和2B。
你需要购买3个A和2个B, 所以你付了¥10购买了1A和2B(大礼包2),以及¥4购买2A。

示例 2:

输入: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1]
输出: 11
解释: 
A,B,C的价格分别为¥2,¥3,¥4.
你可以用¥4购买1A和2B,也可以用¥9购买2A,2B和1C。
你需要买1A,2B和1C,所以你付了¥4买了1A和1B(大礼包1),以及¥3购买1B, ¥4购买1C。
你不可以购买超出待购清单的物品,尽管购买大礼包2更加便宜。

说明:

最多6种物品, 100种大礼包。
每种物品,你最多只需要购买6个。
你不可以购买超出待购清单的物品,即使更便宜。

思路分析: 直接回溯法+剪枝。对于当前需求,我们首先考虑单独购买,更新此时的最小总价。然后再去寻找是否能够购买礼包,达到降低总价的目的。那么剪枝就放在购买大礼包是否超过已经搜索到的最小值。

class Solution {
public:
    int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
        int minRes = INT_MAX;
        dfs(price, special, needs, minRes, 0);
        return minRes;
    }
    //搜索在现有需求nowNeeds下,最小的购买总价,tempRes是从needs状态转移到nowNeeds需求状态已经使用了的金额
    void dfs(vector<int>& price, vector<vector<int>>& special, vector<int>& nowNeeds, int &minRes, int tempRes){
        //nowNeedSum是任然需要购买的物品的总个数
        int nowNeedSum = accumulate(nowNeeds.begin(), nowNeeds.end(), 0), nowNeedsSize = nowNeeds.size();
        //calSumPrice(price, nowNeeds) + tempRes代表的单独购买nowNeeds
        minRes = min(calSumPrice(price, nowNeeds) + tempRes, minRes);
        if (nowNeedSum == 0){
            return;
        }
        //搜索可购买的大礼包
        for (auto &oneSpecial : special){
            //这个礼包必须可以购买,并且购买后的总价不会超过已经找到的最小总价
            if (isCanBuy(oneSpecial, nowNeeds) && tempRes + oneSpecial[nowNeedsSize] <= minRes){
                //进行购买
                for (int index = 0 ;index < nowNeedsSize; ++index){
                    nowNeeds[index] -= oneSpecial[index];
                }
                dfs(price, special, nowNeeds, minRes, tempRes + oneSpecial[nowNeedsSize]);//下一步搜索
                //记得把购买的物品放回去
                for (int index = 0 ;index < nowNeedsSize; ++index){
                    nowNeeds[index] += oneSpecial[index];
                }
            }
        }
    }
    //检测oneSpecial在当前需求nowNeeds下是否能够购买,即礼包oneSpecial中每一物品的数量都得不高于nowNeeds对应的需要的个数
    bool isCanBuy(vector<int> & oneSpecial, vector<int>& nowNeeds){
        int nowNeedsSize = nowNeeds.size();
        for (int index = 0; index < nowNeedsSize; ++index){
            if (nowNeeds[index] < oneSpecial[index]){
                return false;
            }
        }
        return true;
    }
    //单独购买nowNeeds
    int calSumPrice(vector<int>& price, vector<int>& nowNeeds){
        int nowNeedsSize = nowNeeds.size(), resSum = 0;
        for (int index = 0; index < nowNeedsSize; ++index){
            resSum += price[index] * nowNeeds[index];
        }
        return resSum;
    }
};

LeetCode 大礼包(回溯法+剪枝)_第1张图片

你可能感兴趣的:(LeetCode,回溯法)