I was asked a problem which was a variation of the LC combination-sum problem https://leetcode.com/problems/combination-sum/description/
Problem:
A customer at a restaurant wants to order appetizers that total a specific amount. Given a menu with item prices, find and return all possible combinations of items that sum to the target amount. If no combination is found, return an empty list.
Example Menu:
Nachos - $3.50
Spring Rolls - $2.80
Chicken Wings - $4.10
Fries - $3.20
Example #1:
Input: possible_order(6.70)
Output: [["Nachos", "Fries"], ["Spring Rolls", "Chicken Wings"]]
Example #2:
Input: possible_order(9.50)
Output: [["Nachos", "Chicken Wings", "Fries"], ["Nachos", "Spring Rolls", "Chicken Wings"], ["Spring Rolls", "Fries", "Chicken Wings"]]
Solution:
def possible_orders(target: float):
menu = [
("Nachos", 3.50),
("Spring Rolls", 2.80),
("Chicken Wings", 4.10),
("Fries", 3.20)
]
result = []
def backtrack(current_combination, start, current_sum):
if current_sum == target:
result.append(list(current_combination))
return
if current_sum > target:
return
for i in range(start, len(menu)):
item, price = menu[i]
current_combination.append(item)
backtrack(current_combination, i, current_sum + price)
current_combination.pop()
backtrack([], 0, 0)
return result
print(possible_orders(9.50))
print(possible_orders(5.30))
print(possible_orders(10.50))