# 直接遞迴解法,容易超時,python可以加個快取裝飾器,這樣也算是將遞迴轉換成迭代的形式了
# 除了這種方式,還有增加步長來遞迴,變相的減少了重複計算
# 還有一種方法,在遞迴的同時,用陣列記憶之前得到的結果,也是減少重複計算
import functools
class Solution:
@functools.lru_cache(100) # 快取裝飾器
def climbStairs(self, n: int) -> int:
if n < 3:
return n
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
# 直接DP,新建一個字典或者陣列來儲存以前的變數,空間複雜度O(n)
class Solution2:
def climbStairs(self, n: int) -> int:
dp = {}
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
# 還是DP,只不過是只儲存前兩個元素,減少了空間,空間複雜度O(1)
class Solution3:
def climbStairs(self, n: int) -> int:
if n == 1 or n == 2:
return n
a, b = 1, 2
for i in range(3, n + 1):
a, b = b, a + b
return b
# 直接斐波那契數列的計算公式
class Solution4:
def climbStairs(self, n: int) -> int:
import math
sqrt5 = 5 ** 0.5
fibin = math.pow((1 + sqrt5) / 2, n + 1) - math.pow((1 - sqrt5) / 2, n + 1)
return int(fibin / sqrt5)
# 面向測試用例程式設計
class Solution5:
def climbStairs(self, n: int) -> int:
a = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657,
46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465,
14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170,
1836311903]
return a[n - 1]
class Solution6(object):
# 矩陣相乘
def mul(self, a, b):
r = [[0, 0], [0, 0]]
r[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0]
r[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1]
r[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0]
r[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1]
return r
# 遞迴加速計算斐波那契數列 O(n^2) -> O(logn)
def helper(self, n):
if n == 0:
return [[1, 0], [0, 1]]
if n == 1:
return [[1, 1], [1, 0]]
if n & 1 == 0:
return self.mul(self.helper(n // 2), self.helper(n // 2))
else:
return functools.reduce(self.mul, [self.helper((n - 1) // 2), self.helper((n - 1) // 2), [[1, 1], [1, 0]]])
def climbStairs(self, N):
return self.helper(N)[0][0]
for i in range(1, 11):
print(i, Solution6().climbStairs(i))