问题如下:   已经  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), 请问有没有更有效率的办法?
   在线等,  万分感谢!!! 

解决方案 »

  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);        }