4

给定任意数量的有序列表

List<int> list1 = new List<int> {1, 1, 2};
List<int> list2 = new List<int> {1, 2, 3, 4};
List<int> list3 = new List<int> {1, 2};
List<int> listN = new List<int> {....,....};

我想找到列表的组合,以便按升序找到每个组合的总和。例如,

{1, 1, 1} = 3, where {1 (1st element of list1), 1 (1st element of list2), 1 (1st element of list3)} 
{1, 1, 1} = 3, where {1 (2nd element of list1), 1 (1st element of list2, 1 (1st element of list3)}
{1, 2, 1} = 4
{1, 1, 2} = 4
{2, 1, 1} = 4
... 

以升序查找总和的原因是我可以选择只计算前 M 个组合(例如上面的 M = 5)。

我目前的想法是以某种方式扩展查找所有列表的组合,如List<List<int>> 的组合中所讨论的,从列表的一个小子集开始,其中当前元素和下一个元素之间的差异为 0,例如

List<int> tempList1 = new List<int> {1, 1};
List<int> tempList2 = new List<int> {1};
List<int> tempList3 = new List<int> {1};

并找到所有组合,然后将具有最小差异的下一个元素添加到列表中

List<int> tempList1 = new List<int> {1, 1, 2};
List<int> tempList2 = new List<int> {1, 2};
List<int> tempList3 = new List<int> {1, 2};

并从那里构建解决方案集。

这可能吗,有没有更好的方法来做到这一点?

4

2 回答 2

0

计算单个项目并不昂贵,但是如果项目数量很大,则将所有结果保存在内存中并对其进行排序可能会很昂贵。但是,如果我正确理解的话,计算组合似乎对解决任务没有多大帮助。

编辑:当我开始写我的回复时,我没有看到关于组合的说明。无论哪种方式,如果您有不同组合的生成器,也可以使用以下算法。我不确定是否有一个通用的解决方案来只生成想要的总和。

假设 N 是项目数,M 是您想要获得的结果数。为了使以下内容有意义,我假设 N >> M (例如更大)。

然后我会使用以下算法:

  • 创建一个结果列表以容纳最多 M 个项目。
  • 遍历所有 N 项。
    • 对于每个项目,计算总数
    • 在结果列表中插入总数,以便顺序正确(二进制搜索可能是一种很好的算法)
    • 将插入后的结果列表修​​剪为不超过 M 个项目(插入的项目或先前插入的项目将根据它们的计算结果脱落)
  • 您现在拥有前 M 个项目,按降序排列

请注意,如果您愿意,您可以轻松地使上述算法相对于原始 N 项的顺序保持稳定。

于 2012-12-21T17:06:45.380 回答
0

尝试这个:

List<int> list1 = new List<int> { 1, 1, 2 };
List<int> list2 = new List<int> { 1, 2, 3, 4 };
List<int> list3 = new List<int> { 1, 2 };

var combinations = list1
    .SelectMany(x => list2, (a, b) => new { a, b })
    .SelectMany(x => list3, (combined, c) => new { a = combined.a, b = combined.b, c })
    .Select(comb => new{ Sum = comb.a + comb.b + comb.c, Combination = new List<int>{comb.a, comb.b, comb.c}})
    .OrderBy(summed => summed.Sum);

╔═════════════╦═════╗
║ Combination ║ Sum ║
╠═════════════╬═════╣
║ 1,1,1       ║   3 ║
║ 1,1,1       ║   3 ║
║ 1,1,2       ║   4 ║
║ 1,2,1       ║   4 ║
║ 1,1,2       ║   4 ║
║ 1,2,1       ║   4 ║
╚═════════════╩═════╝

编辑:清理了一下

于 2012-12-21T17:14:39.063 回答