剑指offer 菲波那切数列

来源:互联网 发布:树莓派部署python环境 编辑:程序博客网 时间:2024/06/10 01:34
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。

n<=39



解决方案,递归和迭代:

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

public class Solution {    public int Fibonacci(int n) {        int first = 1;        int second = 1;        int result = 1;        if( n==0){            return 0;        }        if( n==1 || n==2){            return 1;        }        while(n > 2){            result = first + second;            first = second;            second = result;            n--;        }        return result;    }}