Leetcode刷题总结:638. Shopping Offers

题目:

给定商品价格、特价组合、要买的商品数量,给出买到指定数量商品的最小花费

Input: [2,5], [[3,0,5],[1,2,10]], [3,2]
Output: 14
Explanation: 
[2,5]表示有两种商品A和B,售价分别是$2,$5
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B.
[3,2] 表示要买3A 和 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.

 

题解:

针对每个special offer,计算使用这个special offer后的花费,如果比minPrice少, 则保存为minPrice;

递归方法实现,如果商品数量是k,special offer的数量是n, 因为原题规定了商品数目最大为6,每个商品最多采购6个,special offer最多是100个;

所以时间复杂度是O(n)

class Solution {
public:
    bool checkvalid(vector<int>& needs, const vector<int>& special) {
        for (int j = 0; j < needs.size(); ++j) {
                if (needs[j]-special[j] < 0) {
                    return false;
                }
        }
        return true;
    }
    int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
        int minPrice = 0;
        for (int i = 0; i < needs.size(); ++i) {
            minPrice += needs[i]*price[i];
        }
       
        for (int i = 0; i < special.size(); ++i) {
            if (checkvalid(needs, special[i])) {
                vector<int> curNeeds;
                for (int j = 0; j < needs.size(); ++j) {
                    curNeeds.push_back(needs[j]-special[i][j]);
                }
                int tempPrice = shoppingOffers(price, special, curNeeds)+special[i][needs.size()];
                minPrice = min(minPrice, tempPrice);
            }
        }

        return minPrice;
    }
};

 

转载于:https://www.cnblogs.com/syjbupt/p/7441792.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值