這題選的是#Easy #Array,看到名字感覺很熟悉,決定今天挑這題來試試!
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).
Example 1:
Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:
Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3:
Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Note:
0 ≤ N ≤ 30.
這題講的是費波那契數,就讓我想到”數學小精靈“,書裡面使用兔子生兔子的例子來解釋費波那契數的邏輯。這本書是我國小的時候看的書,裡面用做夢、簡單故事的方式解釋很多數學計算、排列組合、定理等等,吸引讀者對數學的興趣。直到現在我都還是很喜歡這本書。參考1放上這本書在博客來的連結,不過今天看這本書的狀態是絕版了,或許圖書館會有這本書。
解這題我想到的方式是做遞迴迴圈,讓自己呼叫自己,直到最一開始的F(0)=0, F(1)=1
像撥洋蔥一樣先撥到最裡面那層,再一層層往外數回來,所以應該像這樣:
def fib(self, N: int) -> int:
if N == 0:
return 0
elif N == 1:
return 1
else:
return fib(N-1) + fib(N-2)
結果實際跑了之後發現會有個錯誤,寫:
name error: name fib is not defined
參考1博客來-數學小精靈