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

package array;

public class 变态跳台阶 {
    /**
     * f(n) = 1 + f(1) + f(2) + ... + f(n - 2) + f(n - 1) = 1 + preSum
     * f(0) = 0, f(1) = 1, f(2) = 2
     * 0,1,2,4,8, ...
     * 斐波那契数列,时间复杂度O(n),空间复杂度O(1)
     */
    public int JumpFloorII(int target) {
        if (target <= 0) {
            return 0;
        }
        int preSum = 1, cur = 1;
        for (int i = 2; i <= target; i++) {
            cur = preSum + 1;
            preSum += cur;
        }
        return cur;
    }
}

results matching ""

    No results matching ""