-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoize.java
More file actions
41 lines (38 loc) · 980 Bytes
/
Memoize.java
File metadata and controls
41 lines (38 loc) · 980 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
37
38
39
40
41
package algorithm.DynamicProgramming;
/**
* The type Memoize.
*/
class Memoize
{
/**
* Fib int.
*
* @param n the n
* @param lookupTable the lookup table
* @return the int
*/
public static int fib(int n, int lookupTable[])
{
if (lookupTable[n] == -1) { // Check if already present
// Adding entry to table when not present
if (n <= 1)
lookupTable[n] = n;
else
lookupTable[n] = fib(n - 1, lookupTable) + fib(n - 2, lookupTable);
}
return lookupTable[n];
}
/**
* Main.
*
* @param args the args
*/
public static void main(String args[])
{
int n = 6; // Finding the nth Fibonacci number
int [] lookupTable = new int[n+1];
for (int i = 0; i < n+1; i++)
lookupTable[i] = -1; // Initializing the look up table to have -1
System.out.println(fib(n, lookupTable));
}
}