1. 程式人生 > >斐波那契(遞迴與非遞迴)

斐波那契(遞迴與非遞迴)

遞迴

long jumpFloor(int number) {
    if(number <= 0)
        return 0;
    else if(number == 1 )
        return 1;
    return  jumpFloor(number-1)+jumpFloor(number-2);
}

非遞迴

long jumpF(int number) {
    int result[2] = {0,1};
    if(number < 2)
        return result[number];
    long long  sum = 0;
    long long tmpOne = 1;
    long long tmpTwo = 0;
    for(unsigned int i = 2; i <= number; i++)
    {
        sum = tmpOne + tmpTwo;
        tmpTwo = tmpOne;
        tmpOne = sum;
    }
    return sum;
}