!!!!!【此文章仅仅用于记录自己做题,文章毫无用处⚆_⚆】
【简单】可以在看完题目下,自己写出来
目录
一、题目:![](https://i-blog.csdnimg.cn/blog_migrate/b7e387e645717c1ccdaea1c12fdddd3d.png)
二、解答及代码
1、自己方法(比较简易)
建立新的数组
完整代码:
class Solution {
public int tribonacci(int n) {
int []T=new int[n+1];
if(n>=0) T[0]=0;
if(n>=1)T[1]=1;
if(n>=2)T[2]=1;
for(int i=3;i<=n;i++)
{
T[i]=T[i-1]+T[i-2]+T[i-3];
}
return T[n];
}
}
public class MainClass {//官方主函数
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
int n = Integer.parseInt(line);
int ret = new Solution().tribonacci(n);
String out = String.valueOf(ret);
System.out.print(out);
}
}
}
2官方解法
解法一:动态规划
这种就如同我自己的解法。
复杂度分析
-
时间复杂度:O(n)O(n)O(n)。
-
空间复杂度:O(1)O(1)O(1)。
代码:
class Solution {
public int tribonacci(int n) {
if (n == 0) {
return 0;
}
if (n <= 2) {
return 1;
}
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;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/n-th-tribonacci-number/solution/di-n-ge-tai-bo-na-qi-shu-by-leetcode-sol-kn16/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解法二:矩阵快速幂(复杂度低)
貌似较高级
复杂度分析
-
时间复杂度:O(logn)O(\log n)O(logn)。
-
空间复杂度:O(1)O(1)O(1)。
代码:
class Solution {
public int tribonacci(int n) {
if (n == 0) {
return 0;
}
if (n <= 2) {
return 1;
}
int[][] q = {{1, 1, 1}, {1, 0, 0}, {0, 1, 0}};
int[][] res = pow(q, n);
return res[0][2];
}
public int[][] pow(int[][] a, int n) {
int[][] ret = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
while (n > 0) {
if ((n & 1) == 1) {
ret = multiply(ret, a);
}
n >>= 1;
a = multiply(a, a);
}
return ret;
}
public int[][] multiply(int[][] a, int[][] b) {
int[][] c = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j];
}
}
return c;
}
}