The Tribonacci numbers, commonly denoted T(n) form a sequence, called the Tribonacci sequence, such that each number is the sum of the three preceding ones, starting from 0, 1 and 1. That is,
T(0) = 0, T(1) = 1, T(2) = 1 T(n) = T(n - 1) + T(n - 2) + T(n - 3), for n > 2.
Given n, calculate and return T(n).
Example 1:
Input: n = 3 Output: 2 Explanation: T(3) = T(2) + T(1) + T(0) = 1 + 1 + 0 = 2.
Example 2:
Input: n = 4 Output: 4 Explanation: T(4) = T(3) + T(2) + T(1) = 2 + 1 + 1 = 4.
Example 3:
Input: n = 5 Output: 7 Explanation: T(5) = T(4) + T(3) + T(2) = 4 + 2 + 1 = 7.
Note:
Your algorithm should run in O(n) time and use O(1) space.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check