Add DP implementations

This commit is contained in:
pkdism 2016-11-25 18:36:34 +05:30
parent 5852fc0979
commit 4465288f60
2 changed files with 43 additions and 0 deletions

View File

@ -0,0 +1,19 @@
#include <bits/stdc++.h>
using namespace std;
int fib(int n){
int res[n+1];
res[0] = 0; res[1] = 1;
for(int i=2;i<=n;i++){
res[i] = res[i-1] + res[i-2];
}
return res[n];
}
int main(int argc, char const *argv[])
{
int n;
cout<<"Enter n: ";
cin>>n;
cout<<"Fibonacci number is ";
cout<<fib(n)<<endl;
return 0;
}

View File

@ -0,0 +1,24 @@
#include <bits/stdc++.h>
using namespace std;
int arr[1000000];
int fib(int n){
if(arr[n]==-1){
if(n<=1)
arr[n] = n;
else
arr[n] = fib(n-1) + fib(n-2);
}
return arr[n];
}
int main(int argc, char const *argv[])
{
int n;
cout<<"Enter n: ";
cin>>n;
for (int i = 0; i < n+1; ++i)
{
arr[i] = -1;
}
cout<<"Fibonacci number is "<<fib(n)<<endl;
return 0;
}