Problema
The tribonacci numbers extend the Fibonacci idea to three terms: T(0) = 0, T(1) = 0, T(2) = 1, and from then on T(n) = T(n − 1) + T(n − 2) + T(n − 3). The sequence goes 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, …
Implement tribonacci(n).
Input
n: The index of the term, starting at 0.
Output
Return T(n). Only the last three terms are needed at any time, so a loop with three variables is enough.
Vincoli
0 ≤ n ≤ 74
Esempi
Input:
n = 7
Output atteso:
expected = 13
Input:
long long n = 7;
Output atteso:
long long expected = 13;
Input:
long n = 7;
Output atteso:
long expected = 13;
Spiegazione
The terms are 0, 0, 1, 1, 2, 4, 7, 13, so T(7) = 13.
Input:
n = 2
Output atteso:
expected = 1
Input:
long long n = 2;
Output atteso:
long long expected = 1;
Input:
long n = 2;
Output atteso:
long expected = 1;
Spiegazione
T(2) is the first 1 in the sequence: 1.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Return the first three terms directly.
Suggerimento 2
Keep three variables and shift them along each step.
Suggerimento 3
A recursive solution without memory repeats work and is far too slow.
Complessità attesa
O(n) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.