解题思路:
传统的回溯问题的目标只有一个,就是对应位置的目标,选择或者不选择,这里的回溯显然要复杂些,涉及两个目标,来达到最优解(注意不是最大或者最小,否则用dp更好处理),那么对于两个目标,其实采用的思想还是一样的,相当于在之前单目标的情况下多了一层循环,那么对于这道题,先对只能选择1个的冰淇淋基料开始,然后遍历每个位置的配料,选择一份或两份或者不选,直到遍历结束,判断是否满足更新条件,更新res,最后返回,代码如下:
class Solution {
private:
int res = -1;
public:
int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts, int target) {
for(auto& cost : baseCosts) {
dfs(toppingCosts, target, 0, cost);
}
return res;
}
void dfs(vector<int>& toppingCosts, int target, int index, int sum) {
if(index == toppingCosts.size()) {
if(res == -1 || abs(sum - target) < abs(res - target) || (abs(sum - target) == abs(res - target) && sum < res)) {
res = sum;
}
return;
}
// 不选择当前配料
dfs(toppingCosts, target, index + 1, sum);
// 添加一份当前配料
dfs(toppingCosts, target, index + 1, sum + toppingCosts[index]);
// 添加两份当前配料
dfs(toppingCosts, target, index + 1, sum + toppingCosts[index] * 2);
}
};