[关闭]
@Lin-- 2020-02-05T05:32:01.000000Z 字数 1459 阅读 304

ClimbingStairs

Leetcode


典型的斐波那契数列问题。但是用常规的思维解题无法做到高效。
高效算法思路如下:基本思路公式用矩阵表示:


由中间矩阵第一行有两项得,矩阵必然是二阶矩阵。得:

解得a=1,b=1,c=1,d=0;则矩阵

,斐波那契初始值
那么得

可得,然后是快速乘法和快速幂对常数的计算,时间复杂度为

  1. '''python3
  2. # File: climbStairs.py
  3. # Author: 0HP
  4. # Date: 20200203
  5. # Purpose: solve the problem in website: https://leetcode.com/problems/climbing-stairs/
  6. '''
  7. class Solution:
  8. def Qmul(self,a: int,b: int):
  9. result=0
  10. while b:
  11. if b&1: #b's last bit is 1
  12. result+=a
  13. b=b>>1#b=b/2
  14. a=a<<1#a=a*2
  15. return result
  16. def MatrixMul(self,a: [[]],b: [[]]):
  17. #row of b = col of a
  18. Arow,Brow,Bcol=2,2,2
  19. c=[[0,0],[0,0]]
  20. for i in range(2):
  21. for j in range(2):
  22. c[i][j]=self.Qmul(a[i][0],b[0][j])+self.Qmul(a[i][1],b[1][j])
  23. return c
  24. def MatrixPow(self,a: [[]],b: int):
  25. result=[[1,0],[0,1]]
  26. while b:
  27. if b&1:
  28. result=self.MatrixMul(result,a)
  29. b=b>>1
  30. a=self.MatrixMul(a,a)
  31. return result
  32. def climbStairs(self, n: int) -> int:
  33. if n==1 or n==2:
  34. return n
  35. A=[[1,1],[1,0]]
  36. F=[[2],[1]]
  37. A=self.MatrixPow(A,n-2)
  38. result=self.Qmul(A[0][0],F[0][0])+self.Qmul(A[0][1],F[1][0])
  39. return result
  40. t=Solution()
  41. print(t.climbStairs(6))
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注