剣指offer-階段を跳ぶpython実現

673 ワード


再帰:
def jumpFloor(number):
    if number <= 2:
        return number
    return jumpFloor(number - 2) + jumpFloor(number - 1)

ダイナミックプランニング
def jumpFLoor(number):
    dp = [0] * (number + 1)
    if number == 1:
        return dp[number]
    dp[1] = 1
    dp[2] = 2
    for i in range(3, number + 1):
        dp[i] = dp[i - 1] + dp[i - 2]
    return dp[number]

 
へんたいステップ
繰返し式
f(n) = 1 + f(n - 1) + f(n - 2) + ....... f(1)
f(n) = 2 * f(n - 1)
f(n) = 2**(n - 1) f(1) 
def jumpFloor(number):
    if number == 0:
        return 0
    return 2 ** (number - 1)