剑指offer06--斐波那契数列

来源:互联网 发布:安卓网络监控 编辑:程序博客网 时间:2024/06/10 09:03

题目:求斐波那契数列,也就是f(n)=f(n-1)+f(n-2)的过程

<span style="font-size:18px;">package 剑指offer;// 写一个函数,输入n,求斐波那契数列的地n项//f(n) = 0   n = 0//   = 1      n = 1//   = f(n-1) + f(n-2)     n > 1// 这个真的没有想到啊,使用了非常巧妙的方式来public class Test09 {public static int Fbnq(int n){int result = 2;int prePre = 1;int pre = 1;if(n <= 0)return 0 ;if(n == 1 || n == 2)return 1;for(int i = 3; i <= n; i++){//下面这三步就完成了f(n)=f(n-1)+f(n-2)的过程result = pre + prePre;prePre = pre;pre = result;}return result;}public static void main(String args[]){System.out.println(Fbnq(2));System.out.println(Fbnq(3));System.out.println(Fbnq(7));}}</span><span style="color: rgb(0, 0, 153); font-weight: bold; font-size: 18px;"></span>


越高深,越简单

1 0
原创粉丝点击