剑指 Offer - 9:变态跳台阶

题目描述

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

题目链接:https://www.nowcoder.com/practice/22243d016f6b47f2a6928b4313c85387

解题思路

公式法:F(n) = F(n-1)+F(n-2)+F(n-3)+…+F(1),F(n-1) = F(n-2)+F(n-3)+…+F(1) => F(n) = 2 * F(n-1)

在网上看到这种说法,感觉更加易懂:每个台阶都有跳与不跳两种情况(除了最后一个台阶),最后一个台阶必须跳。所以共用 2^(n-1) 中情况

public class Solution {
    public int JumpFloorII(int target) {
        if (target == 0) return 0;
        // return (int) Math.pow(2, target-1);
        return 1 << (target-1);  // 位移操作,更快
    }
}

你可能感兴趣的:(Java,算法,剑指Offer)