从数列1,2,3.......n 中 随意取几个数,使其和等于 m

  //从数列1,2,3.......n 中 随意取几个数,使其和等于 m
  
        public static void Print(int n, int m, List<int> list = null)
        {
            if (n < 1 || m < 1)
            {
                return;
            }

            for (int i = 1; i <= n; i++)
            {
                if (i < m)
                {
                    List<int> childList = new List<int>();

                    if (list != null)
                    {
                        childList.AddRange(list);
                    }
                    childList.Add(i);

                    Print(i - 1, m - i, childList);
                }
                else if (i == m)
                {
                    if (list != null)
                    {
                        foreach (int j in list)
                        {
                            Console.Write("{0} + ", j);
                        }

                        Console.WriteLine("{0}", m);
                    }
                }
            }
        }

posted @ 2013-08-25 16:49  爱起早的小D  阅读(223)  评论(0编辑  收藏  举报