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   ·   实用小工具   ·   2901 人在线   最高记录 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 11ms · UTC 07:34 · PVG 15:34 · LAX 23:34 · JFK 02:34
Developed with CodeLauncher
♥ Do have faith in what you're doing.