博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
斐波那契数列
阅读量:6911 次
发布时间:2019-06-27

本文共 1176 字,大约阅读时间需要 3 分钟。

解题思路

如果用递归会超时,所以改用数组存,或者直接输出,代码如下

 

题目描述

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

代码实现

1 import java.util.Scanner; 2 public class Solution { 3     public int Fibonacci(int n) { 4         int first = 0; 5         int last = 1; 6         int temp = 0; 7         if(n == 0) 8             return first; 9         if(n == 1)10             return last;11         for(int i = 2; i <= n; i++){12             temp=first+last;13             first = last;14             last = temp;15         }16         return last;17     }18     19     public static void main(String[] args){20         Scanner scanner = new Scanner(System.in);21         Solution solution = new Solution();22         int x = scanner.nextInt();23         System.out.println(solution.Fibonacci(x));24     }25 }

 

用数组实现

1 public class Solution { 2     /* 3      * @param n: an integer 4      * @return: an ineger f(n) 5      */ 6         int[] a = new int[50]; 7     public int fibonacci(int n) { 8          9         if(n<=2)10         return n-1;11         if(a[n]!=0)12         return a[n];13         else14         return a[n]=fibonacci(n-1)+fibonacci(n-2);15     }16 }

 

转载于:https://www.cnblogs.com/wanglinyu/p/8186282.html

你可能感兴趣的文章
linux如何开启telnet服务
查看>>
实战:XtraBackup for mysql 5.6自动还原脚本
查看>>
CentOS https 客户端证书制作
查看>>
hardware information
查看>>
针对云安全从业者的指南系列一:云安全实施企业面临的背景
查看>>
我的友情链接
查看>>
OpenLDAP 客户端部署
查看>>
恢复误删除的ESXi服务器存储VMFS卷
查看>>
Java设计模式01-代理模式
查看>>
用户管理,权限管理
查看>>
C++11 委派构造函数特性怎么使用?
查看>>
saltstck源码安装mysql
查看>>
Linux下安装LoadRunner Agent
查看>>
haproxy+pacemeker
查看>>
db2死锁和锁超时
查看>>
C语言学习总结
查看>>
You don't have permission to access / on this server.
查看>>
C言语二分查找(折半查找)算法及代码
查看>>
输出/输入(I/O)常识点汇总
查看>>
计算机系统介绍
查看>>