每日一道算法题2021-10-18

183 阅读1分钟
JZ71 跳台阶扩展问题
描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。
求该青蛙跳上一个n级的台阶(n为正整数)总共有多少种跳法。

数据范围:1≤n≤20
进阶:空间复杂度 O(1) , 时间复杂度 O(1)

/**
 * f(1) = 1
 * f(2) = f(2-1) + f(2-2);
 * f(3) = f(3-1) + f(3-2) + f(3-3);
 * f(4) = f(4-1) + f(4-2) + f(4-3) + f(4-4)
 * f(n-1) = f(n-2) + f(n-3) + .... + f(0)
 * f(n) = f(n-1) + f(n-2) + f(n-3) + .... + f(0) = 2 * f(n-2);
 * */

public static int jumpFloor2(int target) {
    if (target <= 0) {
        return -1;
    } else if (target == 1) {
        return 1;
    } else {
        return 2 * jumpFloor2(target - 1);
    }
}

/*
 * 假设每个台阶都有两种状态,跳和不跳
 * 去除最后一个台阶是青蛙必须跳的
 * 还剩下n-1个台阶
 * 所以剩余台阶跳和不跳的状态2^(n-1)的可能
 * */
public static int jumpFloor2(int target) {

    return (int)Math.pow(2, target-1);
}