c# - 在列表中查找等于目标的一组数字的算法

标签 c# algorithm

这就是我正在尝试做的事情。我有一个整数列表:

List<int> myList = new List<int>() {5,7,12,8,7};

我还有一个目标:

int target = 20;

我想做的是找到一种方法来创建一个新的整数列表,当它们加在一起时等于我的目标。因此,如果我的目标是 20,我需要这样的列表:

{ 12, 8 }

如果我的目标是 26,那么我会这样:

{ 7, 12, 7 }

每个数字只能使用一次(7 使用两次,因为它在列表中出现了两次)。如果没有解决方案,它应该返回一个空列表。有人知道我如何做这样的事情吗?

最佳答案

这是一个统计问题。您想要找到具有匹配和的所有可能组合。我可以推荐这个也值得一读的项目:

http://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G

然后就简单高效了:

List<int> myList = new List<int>() { 5, 7, 12, 8, 7 };
var allMatchingCombos = new List<IList<int>>();
for (int lowerIndex = 1; lowerIndex < myList.Count; lowerIndex++)
{
    IEnumerable<IList<int>> matchingCombos = new Combinations<int>(myList, lowerIndex, GenerateOption.WithoutRepetition)
        .Where(c => c.Sum() == 20);
    allMatchingCombos.AddRange(matchingCombos);
}

foreach(var matchingCombo in allMatchingCombos)
    Console.WriteLine(string.Join(",", matchingCombo));

输出:

12,8
5,7,8
5,8,7

关于c# - 在列表中查找等于目标的一组数字的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19437855/

相关文章:

c# - 将SQL查询结果数据提前加载到缓存中

c# - 如何将制表符插入到 C# 控制台应用程序的字符串中?

JavaScript - 字母序列

c - 加权区间调度问题和动态规划

python - 检查两个排序的字符串是否在 O(log n) 时间内相等

c# - 在 Entity Framework Core 上转换为 ulong 的 SqlLite 中正确的 RowVersion 模拟

c# - 在用户提供时获取代码中的 Windows 特殊文件夹

c# - 简化空值检查和相等性

javascript - 如何生成只有 7 个字符的 UID 并排除像 imgur.com 这样的重复

java - 如何有效地在网格上选取一条穿过某些点的线