638. Shopping Offers

Problem refer: https://leetcode.com/problems/shopping-offers/description/

Official solution refer: https://leetcode.com/problems/shopping-offers/solution/

 

// My solution:
// A good dp problem.
// The solution has refered to
the official solution
// because I didn't figure out that
how to store the state
// for dynamic plannning until told
to use std::map. // Some optimizations added by myself: // There is no point in using using special offers in needs, // so we only care about the unused offers and ignore the ones that be applyed before // when do the memory search(dynamic planning). class Solution { public: // These two varibles will nerver gonna to be changed, so move its out of the function. vector<int> g_price; vector<vector<int>> g_special; // Store the state of the dynamic plannning. std::map<vector<int>, int> g_ans; std::map<vector<int>, int>::iterator it_g_ans; // The function to do memory search with every state of needs. // The special id is used to pruning. int shop_calc(vector<int> needs, int special_id) { // If the state was already get, return the result directly. it_g_ans = g_ans.find(needs); if (it_g_ans != g_ans.end()) return it_g_ans -> second; // For every new state, just calc the normal price as the initial value. // PS.I also used memory search there at the beginning which leaded to the time limit exceeded. // It really don't need to plannning because the special offers are the variables. int ans = 0; for (int i=0; i<g_price.size(); i++) { if (needs[i] <= 0) continue; ans += needs[i] * g_price[i]; } // To do the memory search with every possible special offers. // The offers which be processed before are no need to join the next search. for (int i=special_id; i<g_special.size();i++) { bool cansp = true; vector<int> next = needs; for (int j=0; j<g_price.size(); j++) { next [j] -= g_special[i][j]; if (next[j] < 0) { cansp = false; break; } } // To figure out the optimized answer for this state. if (cansp) { ans = min(ans, shop_calc(next, i) + g_special[i][g_price.size()]); } } g_ans[needs] = ans; return ans; } int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) { g_price = price; g_special = special; return shop_calc(needs, 0); } };

 

posted @ 2017-11-23 12:40  KRisen  阅读(213)  评论(0编辑  收藏  举报