classSolution { publicinttribonacci(int n) { if (n == 0) { return0; } if (n <= 2) { return1; } intp=0, q = 0, r = 1, s = 1; for (inti=3; i <= n; ++i) { p = q; q = r; r = s; s = p + q + r; } return s; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicclassSolution { publicintTribonacci(int n) { if (n == 0) { return0; } if (n <= 2) { return1; } int p = 0, q = 0, r = 1, s = 1; for (int i = 3; i <= n; ++i) { p = q; q = r; r = s; s = p + q + r; } return s; } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var tribonacci = function(n) { if (n === 0) { return0; } if (n <= 2) { return1; } let p = 0, q = 0, r = 1, s = 1; for (let i = 3; i <= n; ++i) { p = q; q = r; r = s; s = p + q + r; } return s; };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution: deftribonacci(self, n: int) -> int: if n == 0: return0 if n <= 2: return1 p = 0 q = r = 1 for i inrange(3, n + 1): s = p + q + r p, q, r = q, r, s return s
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functribonacci(n int)int { if n == 0 { return0 } if n <= 2 { return1 } p, q, r, s := 0, 0, 1, 1 for i := 3; i <= n; i++ { p = q q = r r = s s = p + q + r } return s }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: inttribonacci(int n){ if (n == 0) { return0; } if (n <= 2) { return1; } int p = 0, q = 0, r = 1, s = 1; for (int i = 3; i <= n; ++i) { p = q; q = r; r = s; s = p + q + r; } return s; } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
inttribonacci(int n) { if (n == 0) { return0; } if (n <= 2) { return1; } int p = 0, q = 0, r = 1, s = 1; for (int i = 3; i <= n; ++i) { p = q; q = r; r = s; s = p + q + r; } return s; }
classSolution: deftribonacci(self, n: int) -> int: if n == 0: return0 if n <= 2: return1 defmultiply(a: List[List[int]], b: List[List[int]]) -> List[List[int]]: c = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for i inrange(3): for j inrange(3): c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j] return c
defmatrix_pow(a: List[List[int]], n: int) -> List[List[int]]: ret = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] while n > 0: if n & 1: ret = multiply(ret, a) n >>= 1 a = multiply(a, a) return ret q = [[1, 1, 1], [1, 0, 0], [0, 1, 0]] res = matrix_pow(q, n) return res[0][2]
func(a matrix) mul(b matrix) matrix { c := matrix{} for i, row := range a { for j := range b[0] { for k, v := range row { c[i][j] += v * b[k][j] } } } return c }
func(a matrix) pow(n int) matrix { res := matrix{} for i := range res { res[i][i] = 1 } for ; n > 0; n >>= 1 { if n&1 > 0 { res = res.mul(a) } a = a.mul(a) } return res }
functribonacci(n int)int { if n == 0 { return0 } if n <= 2 { return1 } m := matrix{ {1, 1, 1}, {1, 0, 0}, {0, 1, 0}, } res := m.pow(n) return res[0][2] }