Advertisement
BojidarDosev

Fibonacci with memoization

Jun 22nd, 2025
378
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.45 KB | None | 0 0
  1.     public static List<Integer> list = new ArrayList<>();
  2.  
  3.     public static int s(int n){
  4.         while (list.size() <= n) {
  5.             list.add(-1); // initialize with a dummy value
  6.         }
  7.  
  8.         if(n<=2){
  9.             list.set(n,1);
  10.             return 1;
  11.         }
  12.  
  13.         if(list.get(n) != -1){
  14.             return list.get(n);
  15.         }
  16.  
  17.         int result = s(n-1)+s(n-2);
  18.         list.set(n,result);
  19.         return result;
  20.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement