1774. Closest Dessert Cost

ss
Feb 28, 2021

--

周賽復盤, 我選用dfs, 並且用一張表紀錄出現過的次數, 每用一次就-1

比較要注意的是 base要也去計算最靠近的result, 因為我們有一種可能是可以不加topping

class Solution {
public:
void dfs(int target, unordered_map<int, int> tc_m, int cur, int &res){
for(auto &t :tc_m){
if(t.second <= 0) continue;
if(cur + t.first > target){
res = abs(cur + t.first - target) < abs(res-target)?cur + t.first:res;
continue;
}
if(cur + t.first == target){
res = cur + t.first;
return;
}
res = abs(cur + t.first - target) < abs(res-target)?cur + t.first:res;
t.second--;
dfs(target, tc_m, cur + t.first, res);
}
}
int closestCost(vector<int>& bcs, vector<int>& tc, int target) {
int res = INT_MAX;
unordered_map<int, int> tc_m;
for(auto t: tc){
tc_m[t] = 2;
}
for(auto bc: bcs){
int t = target - bc;
res = abs(bc - target) < abs(res-target)?bc:res;
dfs(target, tc_m, bc, res);
}
return res;
}
};

--

--

ss
ss

No responses yet