当前位置:编程学习 > C#/ASP.NET >>

一个编程题

输入一个数组,如[0,1,2,20,5,8,4]  输出所有满足之和为20的子数组,如[0,20],[1,2,5,8,4] --------------------编程问答-------------------- 自己顶下。。 --------------------编程问答-------------------- http://bbs.csdn.net/topics/390210420

参考这个 --------------------编程问答-------------------- 为什么是20呢?是不是最大数? 迭代求和这个应该简单多了,我原来问了一个http://bbs.csdn.net/topics/390360329 --------------------编程问答--------------------
    public static void Main()
        {
            int[] arry = { 0, 1, 2, 20, 5, 8, 4 };
            Array.Sort(arry);
            List<int> c = new List<int>();
            List<int[]> lstRes = new List<int[]>();
            printAllCombination(arry, arry.Length, c, lstRes, 0, 20);  //最后一个参数是和
            //lstRes为结果

            Application.Run(new Form1());

        }



        static public void printAllCombination(int[] a, int len, List<int> c, List<int[]>lstRes, int c_sum, int sum)
        {
            if (c_sum == sum)
            {
                lstRes.Add(c.ToArray());
            }
            else if (c_sum < sum)
            {
                for (int p = len - 1; p >= 0; p--)
                {
                    c.Add(a[p]);
                    printAllCombination(a, p, c,lstRes, c_sum + a[p], sum);
                    c.RemoveAt(c.Count - 1);
                }
            }
        }
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,