V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX  ›  coolzqy  ›  全部回复第 1 页 / 共 1 页
回复总数  1
def find_closest_sum_dp(numbers, target):
dp = {0: []}

for num in numbers:
new_dp = dp.copy()
for partial_sum, combo in dp.items():
new_sum = partial_sum + num
if new_sum not in dp or abs(target - new_sum) < abs(target - partial_sum):
new_dp[new_sum] = combo + [num]
dp = new_dp

closest_sum = min(dp, key=lambda x: abs(target - x))
return dp[closest_sum]

numbers = [1, 2, 3, 4, 5]
target = 9
result = find_closest_sum_dp(numbers, target)
print(result)
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1039 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 10ms · UTC 18:44 · PVG 02:44 · LAX 10:44 · JFK 13:44
Developed with CodeLauncher
♥ Do have faith in what you're doing.