名企面试题之泰波那契数列Tribonacci,其定义式为T(n)=T(n-1)+T(n-2)+T(n-3)时间:2022-01-15 13:53:28import java.util.concurrent.TimeUnit;/** * 泰波那契数列 (Tribonacci Number) 即把斐波那契数列 (Fibonacci Number) 的概念推广至三个数。 * T(0)=1, T(1)=1, T(2)=2, T(n)=T(n-1)+T(n-2)+T(n-3), 用最优方式求T(n) * * 文中的三个算法的时间复杂度都是线性的,网上有log(n)级的通过矩阵乘法求解, * 自己还没有看明白,等以后有机会在研究吧 * * @author huoyin * @version 1.0 2010-10-26 下午05:17:32 */public class Tribonacci { private int n1 = 0; private int n2 = 0; private int n3 = 0; /** * 这个方法是最直观的递归式求解,不过性能比较差 */ public int tribonacciNaiveRecursive(int n) { if(n==0 || n==1) { return 1; } else if(n==2) { return 2; } else { int result = tribonacci(n-1) + tribonacci(n-2) + tribonacci(n-3); return result; } } /** * 优化了递归式求解,减少了对中间结果的重复计算 */ public int tribonacciOptimizeRecursive(int n) { if(n==0||n==1) { return 1; } else if(n==2) { n1=1; n2=1; n3=2; return 2; } else { tribonacci(n-1); int n4=n3+n2+n1; n1=n2; n2=n3; n3=n4; return n3; } } /** * 迭代式求解,非递归 */ public int tribonacci(int n) { if(n==0||n==1) { return 1; } else if(n==2) { return 2; } else { n1=1; n2=1; n3=2; int n4 = 0; for(int i=3; i<n; i++) { n4=n3+n2+n1; n1=n2; n2=n3; n3=n4; } return n4; } } public static void main(String[] args) { int n = 16; Tribonacci t = new Tribonacci(); long start = System.nanoTime(); System.out.println(t.tribonacciNaiveRecursive(n)); long end = System.nanoTime(); System.out.printf("Consume Time: %d/n", TimeUnit.MICROSECONDS.convert((end-start), TimeUnit.NANOSECONDS)); start = System.nanoTime(); System.out.println(t.tribonacciNaiveRecursive(n)); end = System.nanoTime(); System.out.printf("Consume Time: %d/n", TimeUnit.MICROSECONDS.convert((end-start), TimeUnit.NANOSECONDS)); start = System.nanoTime(); System.out.println(t.tribonacci(n)); end = System.nanoTime(); System.out.printf("Consume Time: %d/n", TimeUnit.MICROSECONDS.convert((end-start), TimeUnit.NANOSECONDS)); } }