-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnthfibonacci.java
More file actions
36 lines (30 loc) · 951 Bytes
/
nthfibonacci.java
File metadata and controls
36 lines (30 loc) · 951 Bytes
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
/*
Topic- To find nth fibonacci number using Dynamic Programming
Language- Java
Code by- Jai Gaur
Github profile & link- [Jai-Gaur-26](https://github.com/Jai-Gaur-26)
*/
import java.util.*;
public class nthfibonacci {
public static void main(String[] args) throws Exception {
// write your code here
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] strg = new int[n+1]; //storage
int ans = fiboM(n, strg); //M -> memoization
System.out.println(ans);
scn.close();
}
public static int fiboM(int n, int[] strg){
if(n == 0 || n == 1){
return n;
}else if(strg[n] != 0){ //subproblem already solved
return strg[n];
}
int nm1 = fiboM(n-1, strg);
int nm2 = fiboM(n-2, strg);
int nthFib = nm1 + nm2;
strg[n] = nthFib;
return nthFib;
}
}