Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 84ee81f

Browse files
Create fibonacci
1 parent 8fa310f commit 84ee81f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎Dynamic Programming/fibonacci

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include<iostream>
2+
using namespace std;
3+
int fibo_3(int n){
4+
int *ans=new int[n+1];
5+
ans[0]=0;
6+
ans[1]=1;
7+
for(int i=2;i<=n;i++){
8+
ans[i]=ans[i-1]+ans[i-2];
9+
}
10+
return ans[n];
11+
}
12+
int fibo_helper(int n,int* ans){
13+
if(n<=1){
14+
return n;
15+
}
16+
//check if the ouput exists
17+
if(ans[n]!=-1){
18+
return ans[n];
19+
}
20+
//calculate
21+
int a=fibo_helper(n-1,ans);
22+
int b=fibo_helper(n-2,ans);
23+
//save the answer in output
24+
ans[n]=a+b;
25+
//return the answer
26+
return ans[n];
27+
}
28+
int fibo_2(int n){
29+
int *ans=new int[n+1];
30+
for(int i=0;i<=n;i++){
31+
ans[i]=-1;
32+
}
33+
return fibo_helper(n,ans);
34+
}
35+
int fibo(int n){
36+
if(n<=1){
37+
return n;
38+
}
39+
return fibo(n-1)+fibo(n-2);
40+
}
41+
int main(){
42+
int n;
43+
cin>>n;
44+
cout<<fibo_3(n)<<endl;
45+
46+
return 0;
47+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /