-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfibonacci_number.h
More file actions
75 lines (64 loc) · 1.67 KB
/
Copy pathfibonacci_number.h
File metadata and controls
75 lines (64 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#ifndef CPP_ALGORITHM_FIBONACCI_NUMBER_H
#define CPP_ALGORITHM_FIBONACCI_NUMBER_H
#include <vector>
namespace Fibonacci
{
/**
* \brief Calculate the Fibonacci number using a top-down approach.
* \note This is a recursive approach.
* \param number number to calculate
* \param memo memoization of previously calculated numbers
* \return nth Fibonacci number
*/
int FibonacciDynamicTopDown(
int number,
std::vector<int>& memo);
/**
* \brief Calculate the Fibonacci number using a bottom-up approach.
* Use memoization to cache the results.
* \param number number to calculate
* \return nth Fibonacci number
*/
int FibonacciDynamicBottomUp(int number);
}
// ----------------------------------------------------------------------------
inline int Fibonacci::FibonacciDynamicTopDown(
const int number,
std::vector<int>& memo)
{
if (number == 0)
{
return 0;
}
if (number == 1)
{
return 1;
}
if (memo[number] > 0)
{
return memo[number];
}
memo[number] = FibonacciDynamicTopDown(number - 1, memo) + FibonacciDynamicTopDown(number - 2, memo);
return memo[number];
}
// ----------------------------------------------------------------------------
inline int Fibonacci::FibonacciDynamicBottomUp(const int number)
{
if (number == 0)
{
return 0;
}
if (number == 1)
{
return 1;
}
std::vector<int> memo(number + 1, -1);
memo[0] = 0;
memo[1] = 1;
for (int i = 2; i < number; ++i)
{
memo[i] = memo[i - 1] + memo[i - 2];
}
return memo[number - 1] + memo[number - 2];
}
#endif