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
| class Solution { private: int mn = 1e9, ans = 1e9; public: void dfs(vector<int> &a, int id, int sum, int m, int res, int base) { if (id == m) { if (abs(sum - res) < mn) { mn = abs(sum - res); ans = sum + base; } else if (abs(sum - res) == mn) { ans = min(ans, sum + base); } return; } dfs(a, id + 1, sum, m, res, base); dfs(a, id + 1, sum + a[id], m, res, base); dfs(a, id + 1, sum + 2 * a[id], m, res, base); }
int closestCost(vector<int> &baseCosts, vector<int> &toppingCosts, int target) { int m = toppingCosts.size(); for (auto i:baseCosts) { int res = target - i; dfs(toppingCosts, 0, 0, m, res, i); } return ans; } };
|