Problème
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).
Contraintes
0 ≤ n ≤ 90
Exemples
Entrée :
n = 10
Sortie attendue :
expected = 55
Entrée :
long long n = 10;
Sortie attendue :
long long expected = 55;
Entrée :
long n = 10;
Sortie attendue :
long expected = 55;
Explication
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55: F(10) = 55.
Entrée :
n = 0
Sortie attendue :
expected = 0
Entrée :
long long n = 0;
Sortie attendue :
long long expected = 0;
Entrée :
long n = 0;
Sortie attendue :
long expected = 0;
Explication
By definition F(0) = 0.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
The first two values are fixed, so start from the base cases.
Indice 2
Build later values from the two previous ones instead of recomputing recursively.
Indice 3
Use an iterative approach to avoid repeated work and deep recursion.
Complexité attendue
O(n) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.