剑指offer:青蛙跳台阶

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

class Solution:
    """
    f(0) = 1
    f(1) = 1
    ...
    f(n-1) = f(n-2) + f(n-3) + ... + f(1) + f(0)
    f(n) = f(n-1) + f(n-2) + f(n-3) + ... + f(1) + f(0)
         = f(n-1) + f(n-1)
         = 2 * f(n-1)

    f(n) = 2^(n-1), n >= 1
    """
    def jumpFloorRecursive(self, number):
        if number <= 0:
            return -1
        if number == 1:
            return 1
        return 2 * self.jumpFloorRecursive(number - 1)

    def jumpFloorInduction(self, number):
        return 1 << (number - 1)

solution = Solution()
print(solution.jumpFloorInduction(100))

猜你喜欢

转载自blog.51cto.com/jayce1111/2379809
0条评论
添加一条新回复