两种方法。DFS和动态规划
DFS寻找所有可能的路径,当cost已经大于target的时候就不需要再往下走了,再往下一定会花更多钱。
每种配料最多加两次,则在DFS中,对于每个配料的选择有三种0 1 2
class Solution {
public:int res = INT_MAX; // 结果void func(vector& toppingCosts, int index, int target, int cost){// 更新结果if(abs(cost - target) < abs(res - target))res = cost;if(abs(cost - target) == abs(res - target))res = min(res, cost);// 判断结束条件if(cost > target || index == toppingCosts.size())return;// 继续往下走func(toppingCosts, index + 1, target, cost); // 不选择toppingCosts[index]配料func(toppingCosts, index + 1, target, cost + toppingCosts[index]); // 选择一次func(toppingCosts, index + 1, target, cost + toppingCosts[index] * 2); // 选择两次}int closestCost(vector& baseCosts, vector& toppingCosts, int target) {// 以每种基料开始for(int i = 0; i < baseCosts.size(); i++)func(toppingCosts, 0, target, baseCosts[i]);return res;}
};
除了基料必选,其他调料最多选两次。可以转换成一个01背包问题
对于结果的初始化,若最小基料花费为x,则最终结果的取值范围为[x, target * 2 - x],因为一定要选一种基料,所以最小值为最小基料花费x,因为如果有多种方案,选择成本最低的一种,对于一个冰激凌成本最低为只有最小基料花费x,与target的差值为traget - x,则当一个冰激凌的y成本大于target + (target - x)时,其与target的差值y - target大于target - x,则一定不是结果
对大于target的结果,只需要保留一个最小的结果,因为如果大于target后继续添加配料一定会增加成本,一定不是结果
class Solution {
public:int closestCost(vector& baseCosts, vector& toppingCosts, int target) {sort(baseCosts.begin(), baseCosts.end());// 如果最小基料大于target,则最小花费为最小基料if(baseCosts[0] >= target)return baseCosts[0];int n = baseCosts.size(), m = toppingCosts.size();vector dp(target + 1, false);int res = target * 2 - baseCosts[0]; // 边界// 先选基料for(int i = 0; i < n; i++){if(baseCosts[i] > target)res = min(res, baseCosts[i]);else if(baseCosts[i] == target)return baseCosts[i];elsedp[baseCosts[i]] = true;}// 对每种配料进行选取,每种配料选两次int c = 1; // 每种配料选两次for(int i = 0; i < m; i += c){for(int j = target; j > 0; j--){// 对于大于 target的情况,只需要保留一个结果即可if(dp[j] && j + toppingCosts[i] > target)res = min(res, j + toppingCosts[i]);// 更新背包if(j - toppingCosts[i] >= 0 && dp[j - toppingCosts[i]])dp[j] = true;}if(dp[target])return target;c = (c + 1) % 2;}// 在大于target与i的差值范围内寻找,[target - (res - target), target],如果存在则for(int i = target; i >= target - (res - target); i--){if(dp[i])return i;}return res;}
};