/* Basic solution, according to the recursive method, the algorithm's operation time is exponentially increased * This algorithm for similar sub-problems are repeated calculations, and therefore not an efficient algorithm */public class Fibonaccirecursion {//----------- Computes the recursive function of the Fibonacci sequence value--------------public static int fib (int n) {if (n==1| | n==2) {//1th in sequence, 2 digits 1return 1;} return fib (n-1) +fib (n-2);} public static void Main (string[] args) {int i=6; System.out.println ("Fib (" +i+ "):" +fib (i));}}
/* * You can avoid repeated calculations by saving the solution of the calculated sub-problem * that is, using dynamic programming techniques */public class FIBONACCIDP {//----------using Dynamic planning (DP) The value of the Fibonacci sequence is------------public static int fib (int n) {int[] array = new int[n];//used to hold the state in the dynamic planning process array[0] = 1;array[1] = 1 ; for (int i = 2; i < n; i++) array[i] = Array[i-1] + array[i-2];//dynamically planned state-shifted return array[n-1];} public static void Main (string[] args) {System.out.println ("fib (6):" +fib (6));}}
Two ways to solve the Fibonacci sequence: Basic recursive vs dynamic programming