coolzqy 最近的时间轴更新
coolzqy

coolzqy

V2EX 第 630480 号会员,加入于 2023-05-23 23:04:18 +08:00
coolzqy 最近回复了
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   ·   实用小工具   ·   3374 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 14ms · UTC 12:36 · PVG 20:36 · LAX 04:36 · JFK 07:36
Developed with CodeLauncher
♥ Do have faith in what you're doing.