forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFibonacciNos.java
75 lines (58 loc) · 1.22 KB
/
FibonacciNos.java
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
class Solution {
// TC : O(n)
// SC : O(1)
public int fib(int N) {
if(N <= 1)
return N;
int a = 0, b = 1;
int sum = a + b;
for(int i=2;i<=N;i++)
{
sum = a + b;
a = b;
b = sum;
}
return sum;
}
// TC : O(n)
// SC : O(n)
public int fib(int n) {
if(n<=1){
return n;
}
int[] dp = new int[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];
}
// TC : O(n)
// SC : O(n)
// <N , fib(N)>
Map<Integer, Integer> map = new HashMap<>();
public int fib(int n) {
if(map.containsKey(n)){
return map.get(n);
}
if(n==0){
return 0;
} else if(n==1){
return 1;
} else{
int fibNo = fib(n-1) + fib(n-2);
map.put(n, fibNo);
return fibNo;
}
}
public int fib(int n) {
if(n==0){
return 0;
} else if(n==1){
return 1;
} else{
return fib(n-1) + fib(n-2);
}
}
}