![]() |
VOOZH | about |
The tribonacci series is a generalization of the Fibonacci sequence where each term is the sum of the three preceding terms.
a(n) = a(n-1) + a(n-2) + a(n-3)
with
a(0) = a(1) = 0, a(2) = 1.
First few numbers in the Tribonacci Sequence are 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, ....
Given a value n, task is to print first n Tribonacci Numbers.
Examples:
Input : 5
Output : 0, 0, 1, 1, 2
Input : 10
Output : 0, 0, 1, 1, 2, 4, 7, 13, 24, 44
Input : 20
Output : 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768, 10609, 19513
A simple solution is to simply follow recursive formula and write recursive code for it,
0 0 1 1 2 4 7 13 24
Time complexity of above solution is exponential.
A better solution is to use Dynamic Programming.
1) Top-Down Dp Memoization:
0 0 1 1 2 4 7 13 24
2) Bottom-Up DP Tabulation:
0 0 1 1 2 4 7 13 24 44
Time complexity of above is linear, but it requires extra space. We can optimizes space used in above solution using three variables to keep track of previous three numbers.
0 0 0 1 2 4 7 13 24 44
Below is more efficient solution using matrix exponentiation.
0 0 1 1 2 4 7 13 24 44