This is the first program for understanding DP
You must be knowing Fib(n)=Fib(n-1)+Fib(n-2)
Lets see the function calls of Fib(6)
Here we can see Fib(4) is called two times and same goes with Fib(3) and other function calls. So we can reduce our complexity by using arrays for storage....
Just where there is returning condition i.e Fib(0)=0,, we make Fib[0]=0
and make Fib[n]=Fib[n-1]+Fib[n-2] we can avoid unecessary calls to functions again and again.....
Please tell me for any other updates in this article
You must be knowing Fib(n)=Fib(n-1)+Fib(n-2)
Lets see the function calls of Fib(6)
Here we can see Fib(4) is called two times and same goes with Fib(3) and other function calls. So we can reduce our complexity by using arrays for storage....
Just where there is returning condition i.e Fib(0)=0,, we make Fib[0]=0
and make Fib[n]=Fib[n-1]+Fib[n-2] we can avoid unecessary calls to functions again and again.....
#include<stdio.h>
int main()
{
int n=12;
int fib[12];
fib[0]=0;
fib[1]=1;
for(int k=2;k<n;k++)
{
fib[k]=fib[k-1]+fib[k-2];
}
printf("%d",fib[n-1]);
Please tell me for any other updates in this article
No comments:
Post a Comment