-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy path509. Fibonacci Number.cpp
41 lines (38 loc) · 1.11 KB
/
509. Fibonacci Number.cpp
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
/**
The Fibonacci numbers, commonly denoted F(n) form a sequence,
called the Fibonacci sequence,
such that each number is the sum of the two preceding ones,
starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).
**/
//recursive solution
//Runtime: 16 ms, faster than 32.44% of C++ online submissions for Fibonacci Number.
//Memory Usage: 8.5 MB, less than 38.31% of C++ online submissions for Fibonacci Number.
class Solution {
public:
int fib(int N) {
if(N==0 or N==1){
return N;
}else{
return fib(N-1) + fib(N-2);
}
}
};
//dynamic programming
//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Fibonacci Number.
//Memory Usage: 8.6 MB, less than 21.93% of C++ online submissions for Fibonacci Number.
class Solution {
public:
int fib(int N) {
if(N==0 or N==1){
return N;
}
vector<int> arr = {0, 1};
while(arr.size() < N+1){
arr.push_back(arr[arr.size()-1] + arr[arr.size()-2]);
}
return arr[arr.size()-1];
}
};