COMPLEX-B

导航

斐波那契数列的递归和非递归实现

定义: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;
    }
}

posted on 2019-04-18 22:28  COMPLEX-B  阅读(849)  评论(0编辑  收藏  举报