forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
36 lines (36 loc) · 1.19 KB
/
Solution.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
30
31
32
33
34
35
36
class Solution {
public:
const int inf = INT_MAX;
int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts, int target) {
vector<int> arr;
function<void(int, int)> dfs = [&](int i, int t) {
if (i >= toppingCosts.size()) {
arr.push_back(t);
return;
}
dfs(i + 1, t);
dfs(i + 1, t + toppingCosts[i]);
};
dfs(0, 0);
sort(arr.begin(), arr.end());
int d = inf, ans = inf;
// 选择一种冰激淋基料
for (int x : baseCosts) {
// 枚举子集和
for (int y : arr) {
// 二分查找
int i = lower_bound(arr.begin(), arr.end(), target - x - y) - arr.begin();
for (int j = i - 1; j < i + 1; ++j) {
if (j >= 0 && j < arr.size()) {
int t = abs(x + y + arr[j] - target);
if (d > t || (d == t && ans > x + y + arr[j])) {
d = t;
ans = x + y + arr[j];
}
}
}
}
}
return ans;
}
};