递归二:跳台阶

/**
 *题目: 跳台阶
 *描述:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
 *解决方案:方法一:思路:举例说明并从中找到规律,列出台阶数和跳法之后,发现裴波那契列类似
 *     步骤:根据公式写出代码即可。
 *   1  (n=1) 
 * f(n) 2  (n=2)
 *   f(n-1)+f(n-2)  (n>2)
 * */

public class Two {

    public static int fibonacci(int n) {
        if(n<=2) {
            return n;
        }
        int first = 1;
        int second = 2;
        int result = 0;
        for(int i=3;i<=n ;i++) {
            result = first+second;
            first = second;
            second = result;
        }
        return result;
        
    }
}

猜你喜欢

转载自www.cnblogs.com/ZeGod/p/9969259.html
今日推荐