题解 | #斐波那契数列#

斐波那契数列

https://www.nowcoder.com/practice/ee5d403c1172487f8c7915b3c3d924c6

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            int n = in.nextInt();
            System.out.println(fib2(n));
        }
        
    }
    public static int fib(int n){
        if(n<=2){
            return 1;
        }
        else{
            return fib(n-1) + fib(n-2);
        }
    }

    public static int fib1(int n){
        int []nums = new int[n+1];
        nums[1] = 1;
        nums[2] = 1;
        for(int i=3;i<=n;i++){
            nums[i] = nums[i -1]+nums[i-2];
        }
        return nums[n];
    }

    public static int fib2(int n){
        int f1 = 1;
        int f2 = 1;
        int f3 = 2;
        
        if (n<=2){
            return f1;
        }

        for (int i = 3;i<=n;i++){
            f3 = f2+f1;
            f1 = f2;
            f2 = f3;
        }
       
        return f3;
    }
}

全部评论

相关推荐

搞机墨镜猫:科研和竞赛全写成项目经历,另外你项目涉及到的技术栈太杂了,应该对不同岗位强调写不同的技术栈,寒假应该不太好找短期,长期明年3,4月好找很多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务