首页 > 代码库 > 任意数相加求和

任意数相加求和

在网上看到一端代码,觉得很新颖,特此记录下来以供大家学习参考:

用C#写一个函数。功能如下:
任意给定一组数,例如{12,60,-8,99,15,35,17,18},
找出任意数相加(不能重复)之后的结果为35(任意设定)的情况
例如:12+8+15; 35; 17+18。

 

算法如下:

     private static readonly int[] values = {12,60,8,99,15,35,17,18 };
     private const int toltal = 35;

 

       private void Test()
        {
            Array.ForEach(Array.FindAll(values,x=>x==toltal),Console.WriteLine);
            Dictionary<string, int> dic = new Dictionary<string, int>();
            for (int i = 0; i < values.Length; i++)
            {
                dic.Add(values[i].ToString(), i);
            }
            GetString(dic);
            Console.ReadLine();
        }

 

        private static void GetString(Dictionary<string,int> dd)
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            foreach (KeyValuePair<string, int> kv in dd)
            {
                for (int i = kv.Value + 1; i < values.Length; i++)
                {
                    string calc = kv.Key + "+" + values[i];
                    if (Convert.ToInt32(new DataTable().Compute(calc, null)) == toltal)
                    {
                        Console.WriteLine(calc);
                    }
                    dic.Add(kv.Key+"+"+values[i],i);
                }
            }
            if (dic.Count > 0)
                GetString(dic);
        }