class Solution {
/**
* @param n: an integer
* @return an integer f(n)
*/
public int fibonacci(int n) {
if (n == 1){
return 0;
}
if(n == 2){
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2) ;// write your code here
}
}
斐波那契数列,递归,没什么好说的 。
然而,用非递归的方法我是不会的
class Solution {
/**
* @param n: an integer
* @return an integer f(n)
*/
public int fibonacci(int n) {
if (n == 1){
return 0;
}
if(n == 2){
return 1;
}
int temp1 = 0;
int temp2 = 1;
int temp = temp1;
for(int i = 3;i <= n;i++){
temp = temp1;
temp1 = temp2;
temp2 = temp2 + temp;
}
return temp2;// write your code here
}
}
递归的方法总是超时,用这种方法吧还是
非递归的方法我居然做出来了,哎呦喂。