剑指offer10 斐波那契数列

剑指offer10 斐波那契数列

    输入一个整数 n ,求斐波那契数列的第 n 项。
    假定从0开始,第0项为0。(n<=39)

样例

输入整数 n=5 
返回 5

思路1

    递归的方法,重要的是写明确递归结束的条件,C++代码可以正常通过,python代码溢出

AcWing-21 C++ code

    class Solution {
    public:
        int Fibonacci(int n) {
            if(n == 0 || n == 1){
                return n;
            }
            return Fibonacci(n - 1) + Fibonacci(n - 2);
        }
    };

AcWing-21 python code


    class Solution(object):
        def Fibonacci(self, n):
            """
            :type n: int
            :rtype: int
            """
            if n == 0 or n == 1:
                return n
            return self.Fibonacci(n - 1) + self.Fibonacci(n - 2)

思路2

&nobsp;&nobsp;&nobsp;&nobsp;用一个数组记录结果,然后依次迭代计算出n的时候的值
&nobsp;&nobsp;&nobsp;&nobsp;时间复杂度和空间复杂度都为O(n)

AcWing-21 C++ code

    class Solution {
    public:
        int Fibonacci(int n) {
            int res[40];
            res[0] = 0;
            res[1] = 1;
            for(int i = 2; i <= n; i++){
                res[i] = res[i - 1] + res[i - 2];
            }
            return res[n];
        }
    };

AcWing-21 python code

    class Solution(object):
        def Fibonacci(self, n):
            """
            :type n: int
            :rtype: int
            """
            res = []
            res.append(0)
            res.append(1)
            for i in range(2, n+1):
                res.append(res[-1] + res[-2])
            return res[n]

思路3

&nobsp;&nobsp;&nobsp;&nobsp; 用三个变量记录,然后依次迭代计算出n的时候的值。
&nobsp;&nobsp;&nobsp;&nobsp;时间复杂度为O(n),空间复杂度为O(1)

AcWing-21 C++ code

    class Solution {
    public:
        int Fibonacci(int n) {
            if(n == 0 || n == 1){
                return n;
            }
            int res_left = 0;
            int res_right = 1;
            for(int i = 2; i <= n; i++){
                res_left = res_left + res_right;
                swap(res_left, res_right);
            }
            return res_right;
    
        }
    };

AcWing-21 python code

    class Solution(object):
        def Fibonacci(self, n):
            """
            :type n: int
            :rtype: int
            """
            if n == 0 or n == 1:
                return n
            res_left = 0
            res_right = 1
            for i in range(2, n + 1):
                res = res_left + res_right
                res_left = res_right
                res_right = res
            return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值