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
| class Solution { int total = Integer.MAX_VALUE; public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) { dfs(price, special, needs, 0, 0); return total; } private void dfs(List<Integer> price, List<List<Integer>> special, List<Integer> needs, int offerIndex, int cost) { if (cost >= total) return; if (offerIndex == special.size()) { for (int i = 0; i < needs.size(); i++) cost += price.get(i) * needs.get(i); total = Math.min(total, cost); return; }
List<Integer> offer = special.get(offerIndex); if (check(offer, needs)) { for (int i = 0; i < needs.size(); i++) { needs.set(i, needs.get(i) - offer.get(i)); } dfs(price, special, needs, offerIndex, cost + offer.get(price.size())); dfs(price, special, needs, offerIndex + 1, cost + offer.get(price.size())); for (int i = 0; i < needs.size(); i++) { needs.set(i, needs.get(i) + offer.get(i)); } }
dfs(price, special, needs, offerIndex + 1, cost); } private boolean check(List<Integer> offer, List<Integer> needs) { for (int i = 0; i < needs.size(); i++) { if (offer.get(i) > needs.get(i)) return false; } return true; } }
|