【发布时间】:2010-09-20 10:42:10
【问题描述】:
我有一个包含数值的项目列表,我需要使用这些项目求和。我需要你的帮助来构建这样一个算法。下面,有一个用 C# 编写的描述我的问题的示例:
int sum = 21;
List<Item> list = new List<Item>();
list.Add(new Item() { Id = Guid.NewGuid(), Value = 3 });
list.Add(new Item() { Id = Guid.NewGuid(), Value = 5 });
list.Add(new Item() { Id = Guid.NewGuid(), Value = 12 });
list.Add(new Item() { Id = Guid.NewGuid(), Value = 3 });
list.Add(new Item() { Id = Guid.NewGuid(), Value = 2 });
list.Add(new Item() { Id = Guid.NewGuid(), Value = 7 });
List<Item> result = // the items in the list that has the defined sum.
注意:我对结果中的项目数量没有限制。
【问题讨论】:
-
这是 NP 完全问题:称为子集和问题。 en.wikipedia.org/wiki/Subset_sum_problem 。不幸的是,您不会找到任何 简单 解决方案 - 迄今为止发现的最佳解决方案在
O(2 ^ (N/2))中运行。 -
这些值是否需要是可用的最大值?
-
作业标签丢失了吗?
-
谢谢@Ani。我认为你是对的。这很有帮助。
-
@Musa Hafalir,我认为你不知道一些限制,如果你真的没有,那么我们寻找 x % item[i] == 0 然后添加这个项目直到我们有那个总和(x)。所以我认为每个值只能使用一次,这是一个约束。 ;-)
标签: c# .net algorithm list combinations