【剑指offer】【斐波那契数列 】递归还是循环

题目描述:

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

递归实现:

/**
 * 斐波那契数列
 * @author HeMing
 */
public class Fibonacci {
    /*递归实现*/
    private int[] fibonacciArr = new int[39];
    private int notZeroSize = 0;

    public int Fibonacci(int n) {
        if (n<=0) {
            return 0;
            //throw new RuntimeException("\"n\" should not lower 1!");
        }

        if (nreturn fibonacciArr[n-1];
        }
        if (n<3) {
            fibonacciArr[0] = 1;
            fibonacciArr[1] = 1;
            notZeroSize = 2;
            return 1;
        }
        fibonacciArr[n-1] = Fibonacci(n-2) + Fibonacci(n-1);
        notZeroSize = n;
        return fibonacciArr[n-1];
    }
}

循环实现:

/**
 * 斐波那契数列
 * @author HeMing
 */
public class Fibonacci {
    /*循环实现*/
    public int Fibonacci2(int n) {
        if (n<1) {return 0;}
        if (n==1) {return 1;}

        int x = 0;
        int y = 1;
        int result = 0;
        for (int i=2; i<=n; i++) {
            result = x + y;
            x = y;
            y = result;
        }
        return result;
    }
}

注意:

  1. 该递归方法扩展性比较差,递归时注意递归树的依赖关系,重复计算很多,且随着n的变大增长速度很快,所以要先判定该次递归是否已经计算过,若计算过,则直接返回已有的计算结果。
  2. 循环实现比较简单,而且不存在重复计算。

你可能感兴趣的:(剑指offer)