1. 程式人生 > >C#實現整數劃分問題——帶輸出

C#實現整數劃分問題——帶輸出

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace _2_2

{

           classProgram

           {

              static void Main(string[] args)

              {

                  int n;

                  Program pr = new Program();

                  n = int.Parse(Console.ReadLine());

                  long dt = DateTime.Now.Ticks;

                  pr.equationCount(n, n,"");

                  long et = DateTime.Now.Ticks;

                  Console.WriteLine((((double)(et - dt)) / 10000).ToString() +"ms");

                  Console.ReadKey();

              }

              /// <summary>

              /// 整數劃分問題

              /// </summary>

              /// <param name="n"></param>

              /// <param name="m"></param>

              /// <param name="s"></param>

              /// <returns></returns>

              public int equationCount(int n, int m,string s)

              {

                  if (n == 1)

                  {

                     s += ",1";

                     Console.WriteLine(s.Substring(1));

                  }

                  else if (n < m)

                  {

                     equationCount(n, n,s);

                  }

                  else

                  {

                     for (int i = m; i > 0; i--)

                     {

                         string si="";

                         si=s;

                         if (n - i <= 0)

                         {

                            si += ","+ n.ToString();

                            Console.WriteLine(si.Substring(1));

                            continue;

                         }

                         si += "," + i.ToString();

                         equationCount(n - i, i,si);

                     }

                  }

                  return 0;

              }

           }

}