|
| 1 | +packageAlgorithms.dp; |
| 2 | + |
| 3 | +importjava.util.ArrayList; |
| 4 | + |
| 5 | +/************************************************************************* |
| 6 | + * Compilation: javac Fibonacci.java |
| 7 | + * Execution: java Fibonacci N |
| 8 | + * |
| 9 | + * Computes and prints the first N Fibonacci numbers. |
| 10 | + * |
| 11 | + * WARNING: this program is spectacularly inefficient and is meant |
| 12 | + * to illustrate a performance bug, e.g., set N = 45. |
| 13 | + * |
| 14 | + * |
| 15 | + * % java Fibonacci 7 |
| 16 | + * 1: 1 |
| 17 | + * 2: 1 |
| 18 | + * 3: 2 |
| 19 | + * 4: 3 |
| 20 | + * 5: 5 |
| 21 | + * 6: 8 |
| 22 | + * 7: 13 |
| 23 | + * |
| 24 | + * Remarks |
| 25 | + * ------- |
| 26 | + * - The 93rd Fibonacci number would overflow a long, but this |
| 27 | + * will take so long to compute with this function that we |
| 28 | + * don't bother to check for overflow. |
| 29 | + * |
| 30 | + *************************************************************************/ |
| 31 | +publicclassFibonacci { |
| 32 | +publicstaticlongfib(intn) { |
| 33 | +//System.out.println("Enter rec once."); |
| 34 | + |
| 35 | +if (n <=2) { |
| 36 | +return1; |
| 37 | +} |
| 38 | + |
| 39 | +returnfib(n -1) +fib(n -2); |
| 40 | +} |
| 41 | + |
| 42 | +publicstaticArrayList<Integer>fibDp(intn) { |
| 43 | +ArrayList<Integer>ret =newArrayList<Integer>(); |
| 44 | + |
| 45 | +// We use the arrayList to store the result to avoid multiply count. |
| 46 | +for (inti =0;i <n;i++) { |
| 47 | +if (i <=1) { |
| 48 | +ret.add(1); |
| 49 | + }else { |
| 50 | +ret.add(ret.get(i -1) +ret.get(i -2)); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | +returnret; |
| 55 | + } |
| 56 | + |
| 57 | +publicstaticvoidmain(String[]args) { |
| 58 | +intN =5; |
| 59 | + |
| 60 | +System.out.print(fib(5) +" "); |
| 61 | +//for (int i = 1; i <= N; i++) { |
| 62 | +//System.out.print(fib(i) + " "); |
| 63 | +//} |
| 64 | + |
| 65 | +ArrayList<Integer>list =fibDp(500); |
| 66 | +System.out.println(list.toString()); |
| 67 | +} |
| 68 | + |
| 69 | +} |