|

楼主 |
发表于 2025-3-2 23:05:46
|
显示全部楼层
- import itertools
- def find_closest_subset(nums, target):
- closest_sum = 0
- best_subset = []
-
- # 遍历所有可能的组合长度(从1到全部数字)
- for r in range(1, len(nums)+1):
- for subset in itertools.combinations(nums, r):
- current_sum = sum(subset)
- # 如果当前和更接近目标且不超限,则更新最优解
- if current_sum >= target and current_sum > closest_sum:
- closest_sum = current_sum
- best_subset = subset
- return best_subset, closest_sum
- # 输入数据
- numbers = [18,18,16,28,16,48,48,20,20,16,16]
- target = 2534.16
- # 运行算法
- best_subset, closest_sum = find_closest_subset(numbers, target)
- # 输出结果
- print(f"最接近且不超过目标的组合: {best_subset}")
- print(f"和为: {closest_sum}, 与目标差值: {target - closest_sum:.2f}")
复制代码
跑出来的的结果是什么 |
|