1. 程式人生 > >劍指offer:青蛙跳臺階

劍指offer:青蛙跳臺階

elf pre 描述 code floor rec 青蛙跳臺階 int return

題目描述
一只青蛙一次可以跳上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))

劍指offer:青蛙跳臺階