【问题标题】:Find elements in a list that, together add up to a target number查找列表中的元素,这些元素加起来为目标数
【发布时间】:2013-05-18 23:48:21
【问题描述】:

假设我有一个列表:

List<int> _arr = new List<int> {1, 3, 4};

还有4的目标

我想使用给定列表中的 linq 将 {1, 3} 作为 1 + 3 = 4{4} 作为 4 = 4 返回。

我该怎么做?

【问题讨论】:

  • 问题不清楚!!!
  • 假设我有上面提到的列表。我得到了一个数字 a = 4 现在我需要找到总和等于 a 的所有数字集。
  • 如果我理解正确,您想在列表中找到加起来为目标数字的数字组合吗?对吗?
  • 如果你有列表 {1, 2, 2, 3, 3, 4, 5} 怎么办?到目前为止,您尝试过什么?
  • 您想在_arr 中找到一个数字组合,使得这些数字的总和等于a,是吗?不幸的是,我不认为 Linq 是最好的解决方案。最好尝试动态编程

标签: c# linq


【解决方案1】:

一旦我们有了获取枚举器/列表的所有子集的方法,这很容易
(在这里找到:Answer: Most Elegant Way to Get All Subsets of an Array in C#

using System;
using System.Collections.Generic;
using System.Linq;

public static class Program
{
    static void Main(string[] args)
    {
        var test = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

        var target = 6;

        var matches = from subset in test.SubSetsOf()
                      where subset.Sum() == target
                      select subset;

        Console.WriteLine("Numbers: {0}", test.Select(i => i.ToString()).Aggregate((a, n) => a + ", " + n));
        Console.WriteLine("Target: {0}", target);

        foreach (var match in matches)
        {
            Console.WriteLine(match.Select(m => m.ToString()).Aggregate((a, n) => a + " + " + n) + " = " + target.ToString());
        }

        Console.ReadKey();
    }

    public static IEnumerable<IEnumerable<T>> SubSetsOf<T>(this IEnumerable<T> source)
    {
        // Deal with the case of an empty source (simply return an enumerable containing a single, empty enumerable)
        if (!source.Any())
            return Enumerable.Repeat(Enumerable.Empty<T>(), 1);

        // Grab the first element off of the list
        var element = source.Take(1);

        // Recurse, to get all subsets of the source, ignoring the first item
        var haveNots = SubSetsOf(source.Skip(1));

        // Get all those subsets and add the element we removed to them
        var haves = haveNots.Select(set => element.Concat(set));

        // Finally combine the subsets that didn't include the first item, with those that did.
        return haves.Concat(haveNots);
    }
}

输出:

Numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9
Target: 6
1 + 2 + 3 = 6
1 + 5 = 6
2 + 4 = 6
6 = 6

【讨论】:

  • 你能解释一下子集方法吗?
  • 我已经添加了 cmets,它有助于思考一个包含单个元素的集合会发生什么,然后一个包含 2 个元素。
【解决方案2】:

我认为这个问题的最佳解决方案是Dynamic Programming

创建一个二维数组,维度为 [a + 1, _arr.Length]:

  0 1 2 3 4
1
3
4

然后,对于该二维数组中的每一列,填充每个单元格,使得一列的所有单元格的总和等于该列的索引:

  0 1 2 3 4
1 0 1 x 0 1
3 0 0 x 1 1
4 0 0 x 0 0

// Alternative solution
  0 1 2 3 4
1 0 1 x 0 0
3 0 0 x 1 0
4 0 0 x 0 1

这里,x 表示没有解决方案。此外,第 4 列有 2 个解决方案,因此您需要考虑这一点,也许使用 List&lt;int&gt;[a]?

至于如何填写这些单元格准确
0 列将保留所有零,因为它是一种无需总和即可实现的解决方案。
对于列i,您要执行i - n(其中n 是_arr 中的当前数字)

  0 1
1 0 1   // 1 - 1 == 0, so you put 1 in here
3 0 0
4 0 0

  0 1 2
1 0 1 x // 2 - 1 == 1, 1 already has a solution, but you already used the number necessary to solve 1
3 0 0 x
4 0 0 x

如果您有多个1s

  0 1 2
1 0 1 1 //             1 - 1 == 0
1 0 0 1 // 2 - 1 == 1, 1 already has a solution
3 0 0 0
4 0 0 0

// Alternative solution
  0 1 2
1 0 0 1 // 2 - 1 == 1, 1 already has a solution
1 0 1 1 //             1 - 1 == 0
3 0 0 0
4 0 0 0

如果您需要更多关于动态规划的信息:Knapsack Problem Dynamic Programming Algorithm

【讨论】:

    【解决方案3】:

    我认为您不能使用简单的 LINQ 查询来做到这一点。事实上,我很难用成熟的 T-SQL 为这个问题想出一个简单的解决方案!

    问题是您尝试返回的不是单个项目,而是基于可能排列的各种项目集合。

    在这点上,我确实希望有人提出这样的 LINQ 查询,因为有些东西告诉我它会很棒。 ;)

    【讨论】:

    • “我确实希望有人能提出这样的 LINQ 查询,因为有些事情告诉我它会很棒”现在我必须尝试!
    • 个人认为T-SQL对于这类问题来说很糟糕。但这只是我。
    • @Moo-Juice LINQ 是(至少对我而言)一种简化的查询语言。 T-SQL 是一种“完整的”查询语言,因此是我的参考。我也认为这不是解决这个问题的最佳工具,但 OP 确实表示他正在寻找 LINQ 查询......
    【解决方案4】:

    如果您正在寻求一个非常好的和快速的解决方案来解决这个问题,那么您并不孤单。

    这是一个众所周知的 SUBSET SUM 问题。我建议你可以在这里查看维基百科:

    http://en.wikipedia.org/wiki/Subset_sum_problem

    当然,您可以遍历所有可能的子集来寻找总和,但请注意有 (2 ^ CountOfListElements) 个可能的组合。如果列表总是很小,则对其进行编码不会有问题。即使是指数时间解决方案也适用于小集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 2011-04-05
      • 1970-01-01
      • 2011-01-12
      • 2018-12-11
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      相关资源
      最近更新 更多