-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathFibonacci.java
66 lines (49 loc) · 871 Bytes
/
Fibonacci.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.Scanner;
public class Fibonacci {
public static int fibbI(int n) {
if(n==0 || n==1) {
return n;
}
int[] dp = new int[n+1];
dp[0]=0;
dp[1]=1;
//n>2
for(int i=2; i<=n; i++) {
dp[i]=dp[i-1]+dp[i-2];
}
return dp[n];
}
public static int fibb(int n,int dp[]) {
if(n==0 || n==1) {
return n;
}
int ans1,ans2;
if(dp[n-1]==-1) {
ans1=fibb(n-1,dp);
dp[n-1]=ans1;
}
else {
ans1=dp[n-1];
}
if(dp[n-2]==-1) {
ans2=fibb(n-2,dp);
dp[n-2]=ans2;
}
else {
ans2=dp[n-2];
}
int myAns= ans1+ans2;
return myAns;
}
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int n=s.nextInt();
int[] dp=new int[n+1];
for(int i=0; i<dp.length; i++) {
dp[i]=-1;
}
int ans= fibb(n,dp);
dp[n]=ans;
System.out.println(ans);
}
}