The code that is for finding fibonacci sequence can be write easily.Let's consider recursive code for finding fibonacci number set.
import java.util.Scanner;
class fac{
public static void main(String a[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter Your number :");
int n=sc.nextInt();
System.out.print(fibonacci(n));
}
public static int fibonacci(int x){
if(x<2){
return 1;
}
else{
return (fibonacci(x-1)+fibonacci(x-2));
}
}
}
In this stage, there are many same subproblems are calculating again and again.So in this case, time complexity goes to height for large input. Because of that reason , dynamic programming technique was came ...In dynamic programming ,an extra table('lookUp' table) is maintained for storing previous calculated subproblems' values. before calculating next subproblems' value, check whether availability of the answer for the particular subproblem in created table('lookUp' table).If it is in the 'lookUp table', get the answer for particular subproblem. If it is not in the 'lookUp ' table, calculate value of the particular problem and store the 'lookUp ' table. That is the meaning of the dynamic programming technique.There are two ways for performing this technique.
1.Memoization -
memoization is the technique that calculating values of subproblems Top- Down manner.Let's consider the code of fibonacci sequence.
import java.util.Scanner;
class fab{
public static void main(String a[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter Your number :");
int n=sc.nextInt();
int[] lookUp=new int[n];
int i;
for(i=0;i<n;i++){
lookUp[i]=-1;
}
fibonachi(n);
}
public static void fibonachi(int x){
if(lookUp[x]==-1){
if(x<=1){
lookUp[x]=x;
}
else{
lookUp[x]=fibonachi(x-1)+fibonachi(x-2);
}
}
System.out.print(lookUp[x]);
}
}
2.Tabulation - This calculation goes to Bottom to Top manner.At first consider the base case and perform . Then perform the next steps using previous cases.Les's consider fibonacci sequence code with tabulation technique.
import java.util.Scanner;
class fac{
public static void main(String a[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter Your number :");
int n=sc.nextInt();
int[] lookUp=new int[n];
int i;
lookUp[0]=1; // store base case values in the 'lookUp' table
lookUp[1]=1;
for(i=2;i<n;i++){
lookUp[i]=lookUp[i-1]+lookUp[i-2];
}
System.out.print(lookUp[n-1]);
}
}
In this case , base case values are stored at first.then calculates next values using previous ones..In tabulation all the values must be calculated because new value calculated using previous vlues..so memoization is better than tabulation.That's all. I hope, you could get idea.Thank you!