Skip to content

Commit 8e89e76

Browse files
committed
Runtime: 0 ms (Top 100.0%) | Memory: 2.20 MB (Top 10.53%)
1 parent 1f9ce85 commit 8e89e76

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Runtime: 0 ms (Top 100.0%) | Memory: 2.20 MB (Top 10.53%)
2+
3+
impl Solution {
4+
/*
5+
| T(n+2) T(n+1) T(n) | | 1 1 0 | | T(n+3) T(n+2) T(n+1) |
6+
| T(n+1) T(n) T(n-1) | * | 1 0 1 | = | T(n+2) T(n+1) T(n) |
7+
| T(n) T(n-1) T(n-2) | | 1 0 0 | | T(n+1) T(n) T(n-1) |
8+
*/
9+
pub fn tribonacci(n: i32) -> i32 {
10+
match n {
11+
0 => 0,
12+
1 | 2 => 1,
13+
n => {
14+
fn mul(m: &[[i32; 3]; 3], e: &[[i32; 3]; 3]) -> [[i32; 3]; 3] {
15+
let x = |row:usize, col:usize| m[row].iter().zip(e.iter().map(|r| r[col])).map(|(a,b)| a*b).sum();
16+
[[x(0,0), x(0,1), x(0,2)], [x(1,0), x(1,1), x(1,2)], [x(2,0), x(2,1), x(2,2)]]
17+
}
18+
let mut m = [[2, 1, 1], [1, 1, 0], [1, 0, 0]]; // initial matrix
19+
let mut e = [[1, 1, 0], [1, 0, 1], [1, 0, 0]]; // linear operator
20+
let mut n = n - 3;
21+
while n > 0 {
22+
if n & 1 > 0 {
23+
m = mul(&m, &e);
24+
}
25+
e = mul(&e, &e);
26+
n >>= 1;
27+
}
28+
m[0][0]
29+
}
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)