-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path1774.cpp
29 lines (29 loc) · 1.03 KB
/
1774.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
int difference = INT_MAX;
int res = INT_MAX;
void backtracking(vector<int>& toppingCosts, int current, int sum, int target) {
if ((sum - target) > difference) return;
if (current == toppingCosts.size()) {
int currentDiff = abs(sum - target);
if (currentDiff == difference) {
res = min(res, sum);
}
else if (currentDiff < difference) {
difference = currentDiff;
res = sum;
}
}
else {
backtracking(toppingCosts, current + 1, sum, target);
backtracking(toppingCosts, current + 1, sum + toppingCosts[current], target);
backtracking(toppingCosts, current + 1, sum + toppingCosts[current] * 2, target);
}
}
int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts, int target) {
for (auto& baseCost : baseCosts) {
backtracking(toppingCosts, 0, baseCost, target);
}
return res;
}
};