N-th Tribonacci Number

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];
    }

猜你喜欢

转载自www.cnblogs.com/setnull/p/11267346.html
今日推荐