That meager and the number of columns

problem

Fibonacci column
we all know Fibonacci number,
and now asked to enter an integer n,
you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0).
n <= 39

Algorithm 1: recursive

Problems: Possible栈溢出
Here Insert Picture Description

 //递归解决
    public int Fibonacci1(int n) {
        //递归结束的条件
        if (n == 0) {
            return 0;
        } else if (n == 1) {
            return 1;
        } else {
            //
            return Fibonacci1(n - 1) + Fibonacci1(n - 2);
        }
    }

Algorithm 2: Use of non-recursive cycles using

t can be returned through ke Here Insert Picture Description
can find rules: front by two values thus calculated third number, then we can define three pointers

  • prepreNumBefore before the number
  • preNumDigital front
  • resultThe results
    updated values of these three figures in the cycle, there are:
    result=preNum+prepreNum
    prepreNum = preNum
    preNum=result
//用循环
    public  int Fibonacci2(int n){

        //记录袋计算数据前一个的值
        int preNum=1;
        //记录待计算数据前前一个的值
        int prePreNum=0;
        //计算返回结果
        int result=0;
        //这两种情况直接放回
        if(n==0)
            return 0;
        if(n==1)
            return 1;
        //进行循环,求解
        for(int i=2;i<=n;i++){
            //result result为前面一个值与前前一个值
            result=preNum+prePreNum;
            //前前一个值进行更新,为前面一个值
            prePreNum=preNum;
            //前一个值进行更新,为当前计算的结果值,方便进行下一次计算
            preNum=result;
        }
        return result;
    }
He published 198 original articles · won praise 20 · views 20000 +

Guess you like

Origin blog.csdn.net/ZHOUJIAN_TANK/article/details/104901500