P73、面试题9:斐波那契数列

题目一:写一个函数,输入n,求斐波那契数列(Fibonacci)数列的第n项,斐波那契数列的定义如下: f(n) = {0  n = 0;  1   n = 1;  f(n-1)+f(n-2)  n>1}

题目二:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

即求斐波那契数列的f(n)的结果。

在青蛙跳台阶的问题中,如果把条件改成:一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。。。。。它也可以跳上n级,此时该青蛙跳上一个n级的台阶总共有多少种跳法?我们用数学归纳可以证明f(n)=2的n-1次方。

解法一fibonacci_1(效率低下),解法二fibonacci_2(时间复杂度为n)

package com.yyq;

/**
 * Created by Administrator on 2015/9/10.
 */
public class Fibonacci {
    public static long fibonacci_1(int n){
        if(n <= 0) return 0;
        if(n == 1) return 1;
        return fibonacci_1(n - 1) + fibonacci_1( n - 2);

    }

    public static long fibonacci_2(int n){
        if(n <= 0) return 0;
        int result[] = {0,1};
        long fibOne = result[0];
        long fibTwo = result[1];
        long temp = 0;
        if(n <2){
            return result[n];
        }
        for(int i = 2; i <= n; i++) {
            temp = fibOne + fibTwo;
            fibOne = fibTwo;
            fibTwo = temp;
        }
        return temp;
    }

    // ====================测试代码====================
    public static void Test(int n, int expected)
    {
        if(fibonacci_1(n) == expected)
            System.out.println("Test for "+n+" in solution1 passed.");
        else
            System.out.println("Test for " + n + " in solution1 fail.");

        if(fibonacci_2(n) == expected)
            System.out.println("Test for " + n + " in solution2 passed.");
        else
            System.out.println("Test for " + n + " in solution2 fail.");
    }

    public static void main(String[] args){
        Test(0, 0);
        Test(1, 1);
        Test(2, 1);
        Test(3, 2);
        Test(4, 3);
        Test(5, 5);
        Test(6, 8);
        Test(7, 13);
        Test(8, 21);
        Test(9, 34);
        Test(10, 55);
        Test(40, 102334155);
    }
},
 
输出结果:
Test for 0 in solution1 passed.
Test for 0 in solution2 passed.
Test for 1 in solution1 passed.
Test for 1 in solution2 passed.
Test for 2 in solution1 passed.
Test for 2 in solution2 passed.
Test for 3 in solution1 passed.
Test for 3 in solution2 passed.
Test for 4 in solution1 passed.
Test for 4 in solution2 passed.
Test for 5 in solution1 passed.
Test for 5 in solution2 passed.
Test for 6 in solution1 passed.
Test for 6 in solution2 passed.
Test for 7 in solution1 passed.
Test for 7 in solution2 passed.
Test for 8 in solution1 passed.
Test for 8 in solution2 passed.
Test for 9 in solution1 passed.
Test for 9 in solution2 passed.
Test for 10 in solution1 passed.
Test for 10 in solution2 passed.
Test for 40 in solution1 passed.
Test for 40 in solution2 passed.
原文地址:https://www.cnblogs.com/yangyquin/p/4918305.html