🚀

Thanksgiving Sale: Use Coupon Code THANKS25 to Get Extra 25% Off.

00DAYS
:
00HOURS
:
00MINUTES
:
00SECONDS

Leetcode Problem 1774. Closest Dessert Cost

1774. Closest Dessert Cost

Leetcode Solutions

Backtracking with DFS

  1. Initialize a variable closest to store the closest cost found so far, set it to infinity initially.
  2. Iterate over each base flavor cost.
  3. For each base flavor, call the recursive function exploreToppings starting with the current base cost, the toppings array, index 0, and the target.
  4. In exploreToppings, check if the current cost is closer to the target than closest. If so, update closest.
  5. If the current cost is equal to the target, return it immediately as we cannot get any closer.
  6. If the index is out of bounds or the current cost is greater than or equal to the target, return as no further exploration is needed.
  7. Recursively call exploreToppings for the next topping index with 0, 1, and 2 units of the current topping added to the current cost.
  8. After exploring all base flavors and toppings, return the closest cost.
UML Thumbnail

Iterative Combination Enumeration

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...