栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode 509. 斐波那契数 三种方法 java实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode 509. 斐波那契数 三种方法 java实现

LeetCode 509. 斐波那契数 题目描述

LeetCode页面



方法一:常规方法
class Solution {
		public int fib(int n) {
			int res = 0;
			if (n < 2) {
				res = n;
			} else {
				res = fib(n - 1) + fib(n - 2);
			}
			return res;

		}

	}
方法二:滚动数组

参考于LeetCode官方题解

class Solution3 {
		public  int fib(int n) {
			if (n < 2) {
				return n;
			}
			int p = 0, q = 0, r = 1;
			for (int i = 2; i <= n; i++) {
				p = q;
				q = r;
				r = q + r;
			}
			return r;
		}

	}

方法三:通式法

public int fib(int n) {
			double sqrt_5 = Math.sqrt(5);
			double fibN = Math.pow((1 + sqrt_5) / 2 - (1 - sqrt_5 / 2), n);
			return (int) Math.round(fibN / sqrt_5);

		}

参考于LeetCode官方题解

方法四:面向测试编程

class Solution {
    public int fib(int N) {
        if(N==0)
            return 0;
        if(N==1)
            return 1;
        if(N==2)
            return 1;
        if(N==3)
            return 2;
        if(N==4)
            return 3;
        if(N==5)
            return 5;
        if(N==6)
            return 8;
        if(N==7)
            return 13;
        if(N==8)
            return 21;
        if(N==9)
            return 34;
        if(N==10)
            return 55;
        if(N==11)
            return 89;
        if(N==12)
            return 144;
        if(N==13)
            return 233;
        if(N==14)
            return 377;
        if(N==15)
            return 610;
        if(N==16)
            return 987;
        if(N==17)
            return 1597;
        if(N==18)
            return 2584;
        if(N==19)
            return 4181;
        if(N==20)
            return 6765;
        if(N==21)
            return 10946;
        if(N==22)
            return 17711;
        if(N==23)
            return 28657;
        if(N==24)
            return 46368;
        if(N==25)
            return 75025;
        if(N==26)
            return 121393;
        if(N==27)
            return 196418;
        if(N==28)
            return 317811;
        if(N==29)
            return 514229;
        if(N==30)
            return 832040;
        return 0;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/782588.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号