斐波那契数列-剑指Offer

斐波那契数列

题目描述

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

思路

  1. 使用递归会出现重复计算多个值,效率差,在这使用循环,从小忘大计算值,不重复。

代码

public class Solution07 {
    public int Fibonacci(int n) {
        int[] result = {0, 1};
        if (n < 2) {
            return result[n];
        }
        int temp01 = 0;
        int temp02 = 1;
        int fn = 0;
        for (int i = 2; i <= n; i++) {
            fn = temp01 + temp02;
            temp01 = temp02;
            temp02 = fn;
        }
        return fn;
    }

}
原文地址:https://www.cnblogs.com/rosending/p/5610668.html