关于 数据匹配的问题 真心求教
问题如下:已经 result = 10, 数组 A = {1,2,3,4,5,6,7,8,9,10}, 希望能在数组中找出 SUM()= 10 的所有元素。
比如: 1,9 ; 2,8; 10; 等等
现在我想到的办法是 循环组合的方式: 从C(1,10) 到 C(2,10) 直到 C(10,10), 请问有没有更有效率的办法?
在线等, 万分感谢!!!
--------------------编程问答-------------------- 01背包 --------------------编程问答-------------------- 坐等Linq高人 --------------------编程问答-------------------- --------------------编程问答-------------------- 我也只能想到循环的方式…… 等高人 --------------------编程问答--------------------
同等LINQ高手 --------------------编程问答-------------------- 在线等 高人 --------------------编程问答--------------------
+1 标准的背包 --------------------编程问答-------------------- 基本算法啊,背包 --------------------编程问答-------------------- 各位 高手 有没有 背包的算法, 不要递归那种的;
背包问题, 其基本思想 是不是 仍然是 循环? --------------------编程问答-------------------- 求 高手回复 --------------------编程问答-------------------- static void Main(string[] args)
{
int[] values = { 1,2,3,4,5,6,7,8,9,10 };
var testdata = values.Select((n, i) => new { id = i + 1, total = n }).ToArray();
var total = 10;
Func<IEnumerable<int[]>, int[], IEnumerable<int[]>> comb = (x, y) =>
from a in x
from b in y
where a.Count() == 0 || a.Last() < b
select a.Concat(new[] { b }).ToArray();
var indices = Enumerable.Range(0, testdata.Length).ToArray();
var list = new int[][] { new int[] { } }.AsEnumerable();
var result = Enumerable.Range(1, testdata.Length)
.SelectMany(i => list = comb(list, indices))
.Where(c => c.Sum(i => testdata[i].total) == total)
.Select(c => c.Select(i => testdata[i]));
foreach (var c in result)
Console.WriteLine("({0})\t {1} = {2}",
string.Join(", ", c.Select(d => d.id)),
string.Join(" + ", c.Select(d => d.total)),
total);
} --------------------编程问答-------------------- 问题 已用其他方法 解决, 感谢各位的回复
补充:.NET技术 , C#