Problema
The Fibonacci sequence starts 0, 1 and each next number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, …. F(0) = 0 and F(1) = 1.
Implement fibonacci(n).
Input
n: The position in the sequence.
Output
Return F(n).
Vincoli
0 ≤ n ≤ 90
Esempi
Input:
n = 10
Output atteso:
expected = 55
Input:
long long n = 10;
Output atteso:
long long expected = 55;
Input:
long n = 10;
Output atteso:
long expected = 55;
Spiegazione
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55: F(10) = 55.
Input:
n = 0
Output atteso:
expected = 0
Input:
long long n = 0;
Output atteso:
long long expected = 0;
Input:
long n = 0;
Output atteso:
long expected = 0;
Spiegazione
By definition F(0) = 0.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
The first two values are fixed, so start from the base cases.
Suggerimento 2
Build later values from the two previous ones instead of recomputing recursively.
Suggerimento 3
Use an iterative approach to avoid repeated work and deep recursion.
Complessità attesa
O(n) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.