package likou;
/*
* 斐波那契数
* f(0) = 0
* f(1) = 1
* f(n) = f(n-1) + f(n-2);
*/
public class Demo509 {
public static void main(String args[]) {
Demo509 demo = new Demo509();
System.out.println(demo.fib(2));
System.out.println(demo.fibNew(2));
}
public int fib(int n) {
int value = 0;
if(n == 0) {
value = 0;
}else if(n == 1) {
value = 1;
}else {
for(int i=0;i<n;i++) {
value = fib(n-1)+fib(n-2);
}
}
return value;
}
/*
* 时间复杂度比较小
*/
public int fibNew(int n) {
int value = 0;
if(n == 0) {
value = 0;
}else if(n == 1) {
value = 1;
}else {
int pri = 0;
int pri_next = 1;
for(int i=2;i<=n;i++) {
value = pri+pri_next;
pri = pri_next;
pri_next = value;
}
}
return value;
}
}
力扣509-计算斐波那契数
最新推荐文章于 2024-08-18 21:36:31 发布