|
| 1 | +package com.cheehwatang.leetcode; |
| 2 | + |
| 3 | +// Time Complexity : O(n), |
| 4 | +// where 'n' is the input 'n'. |
| 5 | +// The recursive call stack has a maximum height of 'n'. |
| 6 | +// |
| 7 | +// Space Complexity : O(n), |
| 8 | +// where 'n' is the input 'n'. |
| 9 | +// We use a memo of size 'n' to store the tribonacci numbers. |
| 10 | +// Additionally, the recursive call stack has a maximum height of 'n'. |
| 11 | + |
| 12 | +public class NthTribonacciNumber_Recursive { |
| 13 | + |
| 14 | + // Approach: |
| 15 | + // We use the recursive method, using the 'memo' keep track of the calculated number to lower the time complexity. |
| 16 | + |
| 17 | + public int tribonacci(int n) { |
| 18 | + |
| 19 | + // Use an integer array as 'memo' to record the results that was calculated. |
| 20 | + // This is so to not repeat the same calculation over the recursive calls. |
| 21 | + int[] memo = new int[n + 1]; |
| 22 | + return tribonacci(n, memo); |
| 23 | + } |
| 24 | + |
| 25 | + private int tribonacci(int n, int[] memo) { |
| 26 | + if (n == 0 || n == 1) return n; |
| 27 | + if (n == 2) return 1; |
| 28 | + |
| 29 | + // Record the first three element in the Fibonacci sequence. |
| 30 | + memo[1] = 1; |
| 31 | + memo[2] = 1; |
| 32 | + |
| 33 | + // If the ways for n is not recorded in the 'memo' yet, then calculate and record the result into the memo. |
| 34 | + if (memo[n] == 0) { |
| 35 | + memo[n] = tribonacci(n - 1, memo) + tribonacci(n - 2, memo) + tribonacci(n - 3, memo); |
| 36 | + } |
| 37 | + return memo[n]; |
| 38 | + } |
| 39 | +} |
0 commit comments