List <list <int>&gt; </list <int>的有序组合

时间:2012-12-21 16:41:03

标签: c# list combinations

给定任意数量的有序列表

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以上)。

我目前的想法是以某种方式扩展查找所有列表的组合,如Combination of 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};

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

这可能吗,还有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

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

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

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

然后我会使用以下算法:

  • 创建一个结果列表以容纳M个项目。
  • 浏览所有N项。
    • 对于每个项目,计算总数
    • 在结果列表中插入总数以使顺序正确(二进制搜索可能是用于执行此操作的精细算法)
    • 在插入后将结果列表修​​剪为不超过M个项目(插入的项目,或之前列出的项目将根据其计算结果而丢失)
  • 您现在拥有前M个项目,按降序排列

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

答案 1 :(得分: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 ║
╚═════════════╩═════╝

编辑:清理了一下

相关问题