Re: [闲聊] 每日leetcode

楼主: pandix (面包屌)   2024-04-24 10:53:17
※ 引述《Rushia (早瀬ユウカの体操服 )》之铭言:
: https://leetcode.com/problems/n-th-tribonacci-number/description
: 1137. N-th Tribonacci Number
: 给你一个数字n,求出第 n 个 Tribonacci 数列是多少。
没写过快速幂版本 精华区 z-14-2-3-7-4-2 有解释
总之就是用转移矩阵的快速幂把复杂度压成log(n)
Python code:
class Solution:
def tribonacci(self, n: int) -> int:
trans = [[0,1,0],[0,0,1],[1,1,1]]
res = [[0],[1],[1]]
if n < 3:
return res[n][0]
def matmul(a, b, col):
res = [[0]*col for _ in range(3)]
for i in range(3):
for j in range(col):
for k in range(3):
res[i][j] += a[i][k]*b[k][j]
return res
n -= 2
while n:
if n%2:
res = matmul(trans, res, 1)
n //= 2
trans = matmul(trans, trans, 3)
return res[2][0]
作者: Apache (阿帕契)   2024-04-24 10:55:00
精华区怎么有这个
作者: argorok (s.green)   2024-04-24 10:56:00
大师
作者: Rushia (みけねこ的鼻屎)   2024-04-24 11:00:00
面包屌帮写hard

Links booklink

Contact Us: admin [ a t ] ucptt.com