剑指offer——变态跳台阶

剑指offer——变态跳台阶

问题描述

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

思路分析

当台阶为n=1,跳法f(n)=1;
当台阶为n=2,跳法f(n)=2; 方法(1,1)(2)
当台阶为n=3,跳法f(n)=4; 方法(1,1,1)(1,2)(2,1)(3)
当台阶为n=4,跳法f(n)=8; 方法(1,1,1,1)(1,1,2)(1,2,1)(2,1,1)(2,2)
(1,3)(3,1)(4)
观察,其实 f ( n ) = 2 n 1 f(n)=2^{n-1} ,所以
依次类推,可以递归求出n级阶梯跳法之和。f(n)=2*f(n-1);
f ( n ) = { 1 n = 1 f ( n 1 ) 2 n > 1 f(n) = \begin{cases} 1 & n=1 \\ f(n-1)*2 & n>1 \end{cases}
直接用公式,但是效率低。

public class Solution {
    public int JumpFloorII(int target) {
        if(target<=0){
            return 0;
        }
        if(target==1){
            return target;
        }
        return JumpFloorII(target-1)*2;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41246512/article/details/84102679