classSolution {
List<Integer> list = newArrayList<>();
int m;
int t;
publicintclosestCost(int[] baseCosts, int[] toppingCosts, int target) {
intn= baseCosts.length;
m = 2 * toppingCosts.length;
t = target;
getTopCosts(toppingCosts, 0, 0);
intres=0x3f3f3f3f, min = 0x3f3f3f3f;
for (Integer integer : list) {
for (inti=0; i < n; i++) {
intcost= integer + baseCosts[i];
if (Math.abs(target - cost) < min) {
min = Math.abs(target - cost);
res = cost;
}
if (Math.abs(target - cost) == min) {
res = Math.min(res, cost);
}
}
}
return res;
}
privatevoidgetTopCosts(int[] toppingCosts, int k, int sum) {
if (k >= m) {
list.add(sum);
return;
}
getTopCosts(toppingCosts, k + 1, sum + toppingCosts[k % toppingCosts.length]);
getTopCosts(toppingCosts, k + 1, sum);
}
}
dp
classSolution {
publicintclosestCost(int[] baseCosts, int[] toppingCosts, int target) {
intx= Arrays.stream(baseCosts).min().getAsInt();
if (x >= target) {
return x;
}
boolean[] can = newboolean[target + 1];
intres=2 * target - x;
for (int b : baseCosts) {
if (b <= target) {
can[b] = true;
} else {
res = Math.min(res, b);
}
}
for (int t : toppingCosts) {
for (intcount=0; count < 2; ++count) {
for (inti= target; i > 0; --i) {
if (can[i] && i + t > target) {
res = Math.min(res, i + t);
}
if (i - t > 0) {
can[i] = can[i] | can[i - t];
}
}
}
}
for (inti=0; i <= res - target; ++i) {
if (can[target - i]) {
return target - i;
}
}
return res;
}
}
作者:力扣官方题解
链接:https://leetcode.cn/problems/closest-dessert-cost/solutions/2004210/zui-jie-jin-mu-biao-jie-ge-de-tian-dian-2ck06/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧