斐波那契数列的递归和非递归实现
定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)
1.递归
void solution(int n) {
if (n <2)
return n;
else
return solution(n-1) + solution(n-2);
2.非递归
class Solution {
public int fib(int N) {
if (N < 2) return N;
int a = 0;
int b = 1;
int c = 1;
while (N >= 2) {
c = a + b;
a = b;
b = c;
N --;
}
return c;
}
}