首页 技术 正文
技术 2022年11月12日
0 收藏 962 点赞 4,405 浏览 1783 个字
/// <summary>
        /// Use recursive method to implement Fibonacci
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        static int Fn(int n)
        {
            if (n <= 0)
            {
                throw new ArgumentOutOfRangeException();
            }            if (n == 1||n==2)
            {
                return 1;
            }
            return checked(Fn(n - 1) + Fn(n - 2)); // when n>46 memory will  overflow
        }

递归算法时间复杂度是O(n2), 空间复杂度也很高的。当然不是最优的。

自然我们想到了非递归算法了。

一般的实现如下:

        /// <summary>
        /// Use three variables to implement Fibonacci
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        static int Fn1(int n)
        {
            if (n <= 0)
            {
                throw new ArgumentOutOfRangeException();
            }            int a = 1;
            int b = 1;
            int c = 1;            for (int i = 3; i <= n; i++)
            {
                c = checked(a + b); // when n>46 memory will overflow
                a = b;
                b = c;
            }
            return c;
        }

这里算法复杂度为之前的1/n了,比较不错哦。但是还有可以改进的地方,我们可以用两个局部变量来完成,看下吧:

        /// <summary>
        /// Use less variables to implement Fibonacci
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        static int Fn2(int n)
        {
            if (n <= 0)
            {
                throw new ArgumentOutOfRangeException();
            }            int a = 1;
            int b = 1;            for (int i = 3; i <= n; i++)
            {
                b = checked(a + b); // when n>46 memory will  overflow
                a = b - a;
            }
            return b;
        }

好了,这里应该是最优的方法了。

值得注意的是,我们要考虑内存泄漏问题,因为我们用int类型来保存Fibonacci的结果,所以n不能大于46(32位操作系统)

下一篇: TF-IDF 相关概念
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,906
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,430
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,247
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,058
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,690
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,727