In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.

You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.

You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.

Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.

&nbsp;
Example 1:

Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
Output: 14
Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. 
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B. 
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.


Example 2:

Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]
Output: 11
Explanation: The price of A is $2, and $3 for B, $4 for C. 
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. 
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. 
You cannot add more items, though only $9 for 2A ,2B and 1C.


&nbsp;
Constraints:


	n == price.length == needs.length
	1 &lt;= n &lt;= 6
	0 &lt;= price[i], needs[i] &lt;= 10
	1 &lt;= special.length &lt;= 100
	special[i].length == n + 1
	0 &lt;= special[i][j] &lt;= 50


class Solution:
    def shoppingOffers(self, price: List[int], special: List[List[int]], needs: List[int]) -> int:
        def dfs(price, special, needs, memo = {}):
            if tuple(needs) in memo:
                return memo[tuple(needs)]
            res = [sum([p * need for p, need in zip(price, needs)])] # don't use any offer
            for offer in special:
                # check if can apply the offer
                new_needs = []
                for offer_items, need in zip(offer[:-1], needs):
                    new_needs.append(need - offer_items)
                if min(new_needs) < 0:
                    continue
                # Check if without the offer is better
                value = 0
                for p, offer_items in zip(price, offer[:-1]):
                    value += p * offer_items
                if value < offer[-1]:
                    continue
                # Valid Case
                res.append(dfs(price, special, new_needs, memo) + offer[-1])
            memo[tuple(needs)] = min(res)
            return min(res)
        return dfs(price, special, needs)
class Solution {
    public static int fun(int index,List<Integer> price,List<List<Integer>> special, List<Integer> needs){
        // Base 
        if(index < 0){
            int addAmount = 0;
            for(int i=0;i<needs.size();i++){
                addAmount += (needs.get(i) * price.get(i));
            }
            return addAmount;
        }

        // Not Take Offer
        int notTakeOffer = 0 + fun(index-1,price,special,new ArrayList<>(needs));

        // Take Offer 
        int takeOffer = 1000000000;
        if(canTakeOffer(special.get(index),new ArrayList<>(needs))){
            List<Integer> current_special = special.get(index);
            for(int i=0;i<current_special.size()-1;i++){
                int current_need = needs.get(i);
                int update = current_special.get(i);
                needs.set(i,current_need-update);
            }
            takeOffer = current_special.get(current_special.size()-1) + fun(index,price,special,new ArrayList<>(needs));
        }
        return Math.min(notTakeOffer,takeOffer);
    }

    public static boolean canTakeOffer(List<Integer> current_special, List<Integer> needs){
        boolean canTake = true;
        for(int i=0;i<current_special.size()-1;i++){
            if(needs.get(i) < current_special.get(i)){
                canTake = false;
                break;
            }
        }
        return canTake;
    }

    public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        int items = price.size();
        int offers = special.size();
        return fun(offers-1,price,special,needs);
    }
}
/* Note: This code results in a Timeout. */
class Solution {
public:
    int n, c;
    vector<int> dp;
    int compute(const vector<int> &price, const vector<vector<int>> &offers, int needs){
        if(dp[needs] != -1) return dp[needs];
        // Compute the min cost to satisfy these needs
        int best{}, new_needs, i;
        for(int i=0; i<n; i++){
            c = ((needs>>(i*4))&0xf);
            best += c * price[i];
        }
        if(best == 0) return 0;
        for(const vector<int> &offer : offers){
            new_needs = 0;
            for(i=0; i<n; i++){
                c = ((needs>>(i*4))&0xf);
                if(c >= offer[i]) new_needs |= ((c-offer[i])<<(i*4));
                else break;
            };
            if(i == n) best = min(best, compute(price, offers, new_needs) + offer.back());
        }
        return dp[needs] = best;
    }
    int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
        dp.resize((1<<24)+10, -1);
        n = needs.size();
        int needs_hash{};
        for(int i=0; i<n; i++) needs_hash |= ((needs[i])<<(i*4));
        return compute(price, special, needs_hash);
    }
};
/** https://leetcode.com/problems/shopping-offers/
 * @param {number[]} price
 * @param {number[][]} special
 * @param {number[]} needs
 * @return {number}
 */
var shoppingOffers = function(price, special, needs) {
  // Memoization
  this.map = new Map();
  
  return shop(price,special,needs);
};

var shop = function (price, special, needs) {
  // Return memoization result
  if (this.map.has(needs) === true) {
    return this.map.get(needs);
  }
  
  // Calculate total if purchase without special offers
  let currTotal = calcTotal(price, needs);
  
  // Try every single offers
  for(let i = 0; i < special.length; i++) {
    // Check special offer can be used
    if (canUseSpecial(special[i], needs) === true) {
      // Clone the `needs` because we don't want to modify the original `needs`, update the `needs` count by calling `useSpecial()`
      let cloneNeeds = [...needs];
      cloneNeeds = useSpecial(special[i], cloneNeeds);
      
      // Count total if using special offers, basically repeat the same process with updated `needs`
      let totalUsingSpecial = special[i][needs.length] + shop(price, special, cloneNeeds);
      
      // Compare the `currTotal` with total if using special offers
      currTotal = Math.min(currTotal, totalUsingSpecial);
    }
  }
  
  // Update memoization and return result
  this.map.set(needs, currTotal);
  return currTotal;
};

var calcTotal = function (price, needs) {
  // Calculate total if purchase without special offers, basically `price[i] * needs[i]`
  let out = 0;
  
  for (let i =0 ; i < price.length; i++) {
    out += price[i] * needs[i];
  }
  
  return out;
};

var canUseSpecial = function (special, needs) {
  // Check if special offers can be used, if any of `special[i]` is more than `needs[i]`, the special can not be used, return false because we can not buy more than needed
  for (let i = 0; i < needs.length; i++) {
    if (needs[i] < special[i]) {
      return false;
    }
  }
  
  return true;
};

var useSpecial = function (special, needs) {
  // Update the `needs` count by subtracting it from `special`
  for (let i = 0; i < needs.length; i++) {
    needs[i] -= special[i];
  }
  
  return needs;
};
Shopping Offers