当前位置: 首页 > article >正文

Python | Leetcode Python题解之第509题斐波那契数

题目:

题解:

class Solution:
    def fib(self, n: int) -> int:
        if n < 2:
            return n
        
        q = [[1, 1], [1, 0]]
        res = self.matrix_pow(q, n - 1)
        return res[0][0]
    
    def matrix_pow(self, a: List[List[int]], n: int) -> List[List[int]]:
        ret = [[1, 0], [0, 1]]
        while n > 0:
            if n & 1:
                ret = self.matrix_multiply(ret, a)
            n >>= 1
            a = self.matrix_multiply(a, a)
        return ret

    def matrix_multiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]:
        c = [[0, 0], [0, 0]]
        for i in range(2):
            for j in range(2):
                c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j]
        return c

http://www.kler.cn/news/368810.html

相关文章:

  • 安全运营 -- 监控linux命令history
  • 前沿技术与未来发展第一节:C++与机器学习
  • C++——string的模拟实现(上)
  • [LeetCode] 77. 组合
  • pytorch + d2l环境配置
  • Flink CDC系列之:学习理解核心概念——Data Pipeline
  • Shiro授权
  • 网络应用技术 实验一:路由器实现不同网络间通信(华为ensp)
  • 镜舟科技荣获中国信通院 2024 OSCAR 尖峰开源商业化案例奖
  • 模板进阶
  • 深入了解 Android 中的命名空间:`xmlns:tools` 和其他常见命名空间
  • 算法的学习笔记—翻转单词顺序列(牛客JZ73)
  • HarmonyOS Next API12最新版 端云一体化开发-云函数篇
  • 如何快速分析音频中的各种频率成分
  • Vue学习笔记(六)
  • 纯GO语言开发RTSP流媒体服务器-RTSP推流直播、本地保存录像、录像回放、http-flv及hls协议分发
  • linux中级(NFS服务器)
  • Spring Boot集成Shiro授权
  • 极狐GitLab 17.5 发布 20+ 与 DevSecOps 相关的功能【一】
  • mysqld.log文件过大,清理后不改变所属用户
  • c++设计通信类
  • react 总结+复习+应用加深
  • P11227 [CSP-J 2024] 扑克牌(民间数据)
  • 环 境 配 置
  • 【递归、回溯及搜索】No.4---综合练习
  • 【Spring MVC】请求参数的传递