0007 Fibonacci number
Title Description
- We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0). n <= 39
Topics address
- https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3
Report problem-solving
Based on recursive
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
/**
* 微信公众号"小猿刷题"
*/
public int Fibonacci(int N) {
if(N == 0){
return 0;
}
if(N == 1){
return 1;
}
return Fibonacci(N-2) + Fibonacci(N-1);
}
Based on the array to achieve
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
/**
* 微信公众号"小猿刷题"
*/
public int Fibonacci(int N) {
if(N == 0){
return 0;
}
if(N == 1){
return 1;
}
int [] arr = new int[N+1];
arr[0] = 0;
arr[1] = 1;
for(int i = 2; i <= N; i++){
arr[i] = arr[i-2] + arr[i-1];
}
return arr[N];
}
Based on exchange realized
This problem solution by the micro-channel public number
小猿刷题
provided wrong, please correct me.
/**
* 微信公众号"小猿刷题"
*/
public int Fibonacci(int N) {
if(N == 0){
return 0;
}
if(N == 1){
return 1;
}
int a = 0;
int b = 1;
for(int i = 2; i <= N; i++){
int sum = a + b;
a = b;
b = sum;
}
return b;
}