-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path27thJune(I).java
More file actions
39 lines (35 loc) · 1.01 KB
/
Copy path27thJune(I).java
File metadata and controls
39 lines (35 loc) · 1.01 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
public class Fibonacci {
static int fib(int n, int[] cache){
// TC with dp = O(n) ...... TC without DP and simple recursion = O(2^n)
// top down - memoization
if(n==0 || n==1){
return n;
}
//important line of DP
// if n is already calculated then return it ... no further calculations
if(cache[n]!=0){
return cache[n];
}
int first = fib(n-1, cache);
int second = fib(n-2, cache);
int sum = first + second;
//saving the solution
cache[n] = sum;
return cache[n];
}
// using tabulation
// same we did in pascal trainagle
static int fibtabulation(int n , int cache[]){
cache[0]=0;
cache[1]=1;
for(int i = 2; i<=n;i++){
cache[i]=cache[i-1]+cache[i-2];
}
return cache[n];
}
public static void main(String[] args) {
int n = 10;
int[] cache = new int[n+1];
System.out.println(fib(n, cache));
}
}