剑指 Offer - 7:斐波那契数列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AnselLyy/article/details/83743941

题目描述

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

题目链接:https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3

解题思路

迭代或递归思路,但由于 n 较大,递归会爆栈

public class Solution {
    public int Fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1 || n == 2) return 1;
        int[] result = new int[n+1];
        result[1] = 1;
        result[2] = 1;
        for (int i = 3; i < n+1; i++) {
            result[i] = result[i-1] + result[i-2];
        }
        return result[n];
    }
}

猜你喜欢

转载自blog.csdn.net/AnselLyy/article/details/83743941