[剑指Offer]笔记7.斐波那契数列 C++实现

Problem Description

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39

Mentality

斐波那契数列定义为:
F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3,n∈N*)
1、1、2、3、5、8、13、21、34、……
首先想到第一个方法是简单粗暴的递归,但是消耗资源较多,于是进行优化,通过for循环和两个变量来代替递归。

Code (C++)

递归方法:

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

改进方法:

class Solution {
public:
    int Fibonacci(int n) {
        if(n<=1)
        	return n;
		
		int ans=0;
		int temp1=0;
		int temp2=1;
		for(int i=2; i<=n; i++){
			ans=temp1+temp2;
			temp1=temp2;
			temp2=ans;
		}
		return ans;
    }
};

已通过所有的测试用例,欢迎指正批评(´▽`ʃ♡ƪ)

发布了19 篇原创文章 · 获赞 10 · 访问量 1201

猜你喜欢

转载自blog.csdn.net/qq_38655181/article/details/105405653