动态规划对比递归----以求斐波那契数列为例

下面是递归方式:

private static int Fib_RE(int n)
        {
            re_Count++;

            if(n<=1)
            {
                return 1;
            }
            else
            {
                return Fib_RE(n-1) + Fib_RE(n-2);
            }
        }

下面是动态规划:

private static int Fib_Fast(int n,Dictionary<int, int> dic)
        {
            fa_Count++;
            if(!dic.ContainsKey(n))
            {
                dic.Add(n, Fib_Fast(n-1,dic)+Fib_Fast(n-2,dic));
            }

            return dic[n];
        }

 

测试过程:

            const int NUM = 40;

            Stopwatch sw = new Stopwatch();
            sw.Start();

            int result_re = Fib_RE(NUM);

            sw.Stop();


            Console.WriteLine(" Fib_RE({0})={1}:  time: {2}, times: {3}", NUM,result_re, sw.ElapsedTicks, re_Count);

            sw.Reset();
            sw.Start();

            Dictionary<int, int> dic = new Dictionary<int, int>();

            dic.Add(0,1);
            dic.Add(1,1);

            int result_fa = Fib_Fast(NUM,dic);

            sw.Stop();
            Console.WriteLine(" Fib_Fast({0})={1}: time: {2}, times: {3}", NUM,result_fa, sw.ElapsedTicks, fa_Count);

 

结果:

 

时间将近2万倍。。。。。。

posted @ 2015-07-14 13:22  LouisGuo  阅读(179)  评论(0编辑  收藏  举报