斐波那契数列如何快速计算-动态规划法

下面的代码使用C#写的:

    class Program
{
    static void Main(string[] args)
    {
        Program a = new Program();
        DateTime strat = DateTime.Now;
        long kkkk = a.Fibnacci(10);
        TimeSpan s = DateTime.Now - strat;
        Console.WriteLine(s.TotalMilliseconds + " = " + kkkk);

        strat = DateTime.Now;
        List cc = new List();
        kkkk = a.Fibnacci2(50, cc);
        s = DateTime.Now - strat;
        Console.WriteLine(s.TotalMilliseconds + " = " + kkkk);

        Console.ReadKey();
    }

    long Fibnacci(long n) {
        if (n == 0 || n == 1)
        {
            return 1;
        }
        else
        {
            return this.Fibnacci(n - 1) + this.Fibnacci(n - 2);
        }
    }


    long Fibnacci2(long n, List k)//动态规划法
    {
        if (n == 0 || n == 1)
        {
            return 1;
        }
        else
        {
            if (n - 2 >= k.Count)
            {
                k.Add(this.Fibnacci2(n - 1 , k) + this.Fibnacci2(n - 2, k));
            }

            return k[(int)n -2];
        }
    }
}

你可能感兴趣的:(斐波那契数列如何快速计算-动态规划法)