码迷,mamicode.com
首页 > 其他好文 > 详细

N-th Tribonacci Number

时间:2019-07-30 00:24:40      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:ash   map   shm   put   ott   value   better   otto   --   

The Tribonacci sequence Tn is defined as follows:

T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.

Given n, return the value of Tn.

我写的code:

    Map<Integer, Integer> map = new HashMap<>();
    public int tribonacci(int n) {
        if (n == 0) {
            return 0;
        }
        if (n == 1 || n == 2) return 1;
        if (map.containsKey(n)) return map.get(n);
        int sum = tribonacci(n - 1) + tribonacci(n - 2) + tribonacci(n - 3);
        map.put(n, sum);
        return sum;
    }

别人的code:

    public int tribonacci(int n) {
        if (n < 2) return n;
        int a = 0, b = 1, c = 1, d;
        while (n-- > 2) {
            d = a + b + c;
            a = b;
            b = c;
            c = d;
        }
        return c;
    }
    public static int tribonacci(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 1;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
        }
        return dp[n];
    }
    // Recursion is slow. Memorization is better, but bottom up approach is the best here.

    public int tribonacci(int n) {
        int[] t = new int[] {0,1,1};
        
        for (int i = 3; i <= n; i++) {
            int sum = t[0] + t[1] + t[2];
            t[0] = t[1];
            t[1] = t[2];
            t[2] = sum;
        }
        
        return t[2];
    }

N-th Tribonacci Number

标签:ash   map   shm   put   ott   value   better   otto   --   

原文地址:https://www.cnblogs.com/setnull/p/11267346.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!