用遞歸實現python
def fibonacci(n): if n <= 0: return 0 if n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2)
不過這種方法在leetcode上超時了。面試
用循環實現code
class Solution: def fib(self, n: int) -> int: if n <= 0: return 0 if n == 1: return 1 tmp = 0 fibNMinusOne = 1 fibNMinusTwo = 0 for i in range(2, n+1): tmp = fibNMinusOne + fibNMinusTwo fibNMinusTwo = fibNMinusOne fibNMinusOne = tmp return tmp
思路:把它轉化爲一個Fibonacci問題。blog
設青蛙跳n級臺階,共numWays(n)種方法;遞歸
若是青蛙第一次跳一級臺階,則剩下的n-1級臺階共numWays(n-1)種跳法;ci
若是青蛙第一次跳兩級臺階,剩下的n-2級臺階共numWays(n-2)種跳法;leetcode
故numWays(n) = numWays(n-2) + numWays(n-1),即爲遞推公式。io
代碼class
class Solution: def numWays(self, n: int) -> int: res = [1, 1, 2] if n <= 2: return res[n] fibN = 0 fibNMinusTwo = 1 fibNMinusOne = 2 for i in range(3, n+1): fibN = fibNMinusOne + fibNMinusTwo fibNMinusTwo = fibNMinusOne fibNMinusOne = fibN return fibN%1000000007