-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path509+Fibonacci Number.cpp
More file actions
53 lines (44 loc) · 947 Bytes
/
Copy path509+Fibonacci Number.cpp
File metadata and controls
53 lines (44 loc) · 947 Bytes
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
class Solution {
public:
int fib(int n) {
if (n <= 1) return n;
vector<int> dp(n+1);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
};
class Solution {
public:
int fib(int n) {
if (n <= 1) return n;
vector<int> dp(3);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[2] = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = dp[2];
}
return dp[2];
}
};
//best array cost less space than vector
class Solution {
public:
int fib(int n) {
if (n <= 1) return n;
int dp[3];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; ++i) {
dp[2] = dp[0] + dp[1];
dp[0] = dp[1];
dp[1] = dp[2];
}
return dp[2];
}
};