劍指offer(第二版)讀書筆記以及編程題目python版答案(二)
github地址:https://github.com/ciecus/leetcode_answers/tree/master/jianzhi_offer
題目五:青蛙跳臺階
書 p77
github代碼名稱:t5_frog_steps.py
一隻青蛙一次可以跳上1階臺階,也可以跳上2階臺階。求該青蛙跳上一個n階臺階總共有多少種跳法?
輸入格式:
臺階數 n
輸出
跳法 m
思路
構建一個列表進行查找
0 | 1 | 2 | 3 | 4 | n | |
---|---|---|---|---|---|---|
1 | 1 | 2 | f(1)+f(2) | f(2)+f(3) | \dots | f(n-1)+f(n-2) |
通過測試用例代碼
class Solution:
def jumpFloor(self, n):
if not isinstance(n,int):
return 'wrong input'
else:
if n in {0,1}:
return 1
elif n == 2:
return 2
else:
list_ = [1 for i in range(n+1)]
for i in range(2,n+1):
list_[i] = list_[i-1]+list_[i-2]
return list_[n]