You would like to make dessert and are preparing to buy the ingredients. You have n
ice cream base flavors and m
types of toppings to choose from. You must follow these rules when making your dessert:
- There must be exactly one ice cream base.
- You can add one or more types of topping or have no toppings at all.
- There are at most two of each type of topping.
You are given three inputs:
baseCosts
, an integer array of lengthn
, where eachbaseCosts[i]
represents the price of theith
ice cream base flavor.toppingCosts
, an integer array of lengthm
, where eachtoppingCosts[i]
is the price of one of theith
topping.target
, an integer representing your target price for dessert.
You want to make a dessert with a total cost as close to target
as possible.
Return the closest possible cost of the dessert to target
. If there are multiple, return the lower one.
Example 1:
Input: baseCosts = [1,7], toppingCosts = [3,4], target = 10 Output: 10 Explanation: Consider the following combination (all 0-indexed): - Choose base 1: cost 7 - Take 1 of topping 0: cost 1 x 3 = 3 - Take 0 of topping 1: cost 0 x 4 = 0 Total: 7 + 3 + 0 = 10.
思路:注意题目意思是,每种topping最多只能要两个,种类不限制,那么就是每种有0,1,2三种选择;两种choice update res,一种是跟taret的绝对值小于res, 另外一种是相等的话,cursum < res;
class Solution {
public int closestCost(int[] baseCosts, int[] toppingCosts, int target) {
int[] res = new int[]{Integer.MAX_VALUE};
for(int i = 0; i < baseCosts.length; i++) {
dfs(baseCosts[i], target, toppingCosts, 0, res);
}
return res[0];
}
private void dfs(int cursum, int target, int[] toppingCosts, int index, int[] res) {
if(Math.abs(target - cursum) < Math.abs(target - res[0]) ||
(Math.abs(target - cursum) == Math.abs(target - res[0]) && cursum < res[0])) {
res[0] = cursum;
}
if(index == toppingCosts.length || cursum > target) {
return;
}
dfs(cursum, target, toppingCosts, index + 1, res);
dfs(cursum + toppingCosts[index], target, toppingCosts, index + 1, res);
dfs(cursum + 2 * toppingCosts[index], target, toppingCosts, index + 1, res);
}
}