题目:
给定商品价格、特价组合、要买的商品数量,给出买到指定数量商品的最小花费
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; } };