Approach
Depth-first search
For Shopping Offers, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 35 lines of Java from the credited upstream file 638.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 5 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {3 return dfs(price, special, needs, 0);4 }5 6 private int dfs(List<Integer> price, List<List<Integer>> special, List<Integer> needs, int s) {7 int ans = 0;8 for (int i = 0; i < needs.size(); ++i)9 ans += needs.get(i) * price.get(i);10 11 for (int i = s; i < special.size(); ++i) {12 List<Integer> offer = special.get(i);13 if (isValid(offer, needs)) {14 15 for (int j = 0; j < needs.size(); ++j)16 needs.set(j, needs.get(j) - offer.get(j));17 ans = Math.min(ans, offer.get(offer.size() - 1) + dfs(price, special, needs, i));18 19 for (int j = 0; j < needs.size(); ++j)20 needs.set(j, needs.get(j) + offer.get(j));21 }22 }23 24 return ans;25 }26 27 28 private boolean isValid(List<Integer> offer, List<Integer> needs) {29 for (int i = 0; i < needs.size(); ++i)30 if (offer.get(i) > needs.get(i))31 return false;32 return true;33 }34}35