1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| class Solution { public: map<vector<int>, int> memo;
int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) { int n = price.size();
vector<vector<int>> filterSpecial; for (auto & sp : special) { int totalCount = 0, totalPrice = 0; for (int i = 0; i < n; ++i) { totalCount += sp[i]; totalPrice += sp[i] * price[i]; } if (totalCount > 0 && totalPrice > sp[n]) { filterSpecial.emplace_back(sp); } }
return dfs(price, special, needs, filterSpecial, n); }
int dfs(vector<int> price,const vector<vector<int>> & special, vector<int> curNeeds, vector<vector<int>> & filterSpecial, int n) { if (!memo.count(curNeeds)) { int minPrice = 0; for (int i = 0; i < n; ++i) { minPrice += curNeeds[i] * price[i]; } for (auto & curSpecial : filterSpecial) { int specialPrice = curSpecial[n]; vector<int> nxtNeeds; for (int i = 0; i < n; ++i) { if (curSpecial[i] > curNeeds[i]) { break; } nxtNeeds.emplace_back(curNeeds[i] - curSpecial[i]); } if (nxtNeeds.size() == n) { minPrice = min(minPrice, dfs(price, special, nxtNeeds, filterSpecial, n) + specialPrice); } } memo[curNeeds] = minPrice; } return memo[curNeeds]; } };
|