日期:2014-05-17  浏览次数:21086 次

算法!用C#写一个函数,在一个数组中找出随意几个值相加等于一个值
比如,数组{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}  
要找出那些数相加等于20,
请各位大侠不吝赐教,谢谢

------解决方案--------------------
int[] myarray = { 1, 2,3,4,5,6,7,8,9,10,11 };
List<List<int>> mylist = new List<List<int>>();
int length = myarray.Length;
for (int i = 0; i < Math.Pow(2, length); i++)
{
List<int> myint = new List<int>();
for (int j = 0; j < length; j++)
{
if (Convert.ToBoolean(i & (1 << j)))
myint.Add(myarray[j]);
}
mylist.Add(myint);
}
foreach (var a in mylist)
{
if (a.Sum() == 20)
{
foreach (var b in a)
{
Console.Write(b); Console.Write(",");
}
Console.WriteLine();
}
------解决方案--------------------
给你写个例子:
C# code
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {

        static void Main(string[] args)
        {
            double[] myarray = { 1.1, 2.5, 3.3, 4.9, 5.8, 6.8, 7.5, 8.7, 9.4, 10.7, 11.2, 12.9, 13.6, 14.8, 15.9, 16.4, 17.7, 18.4, 19.2 };
            int cnt = 0;
            foreach (var result in 寻找组合(myarray, 50.8, myarray.Length - 1))
            {
                Console.Write("结果{0}==> ", ++cnt);
                foreach (var n in result)
                    Console.Write("{0} ", n);
                Console.WriteLine();
            }
            Console.WriteLine("--------------End");
            Console.ReadKey();
        }

        static IEnumerable<IEnumerable<double>> 寻找组合(double[] array, double sum, int index)
        {
            if (index >= 0)
            {
                foreach (var sub in 寻找组合(array, sum, index - 1))
                    yield return sub;
                foreach (var sub in 寻找组合(array, sum - array[index], index - 1))
                    yield return sub.Concat(new double[] { array[index] });
                if (Math.Abs(array[index] - sum) <= double.Epsilon)
                    yield return new double[] { array[index] };
            }
        }

    }
}

------解决方案--------------------
探讨

测试过了 结果为:
C# code
static int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };


private static void Test(int index, int value,string str,int sum)
……