java retain information in recursive function

后端 未结 8 1991
滥情空心
滥情空心 2020-12-29 09:05

Is it possible to retain information via a helper function with java, without using static variables.

For example,

public void foo(){
    int v = 0;
         


        
8条回答
  •  难免孤独
    2020-12-29 09:40

    I think this is called memoization. It looks like

    class Fibonacci
    {
         public Map < Integer , Integer > memorized = new HashMap < > ( ) ;
    
         public int fib ( int n )
         {
               if ( memoized . containsKey ( n ) )
               {
                     return memoized . get ( n ) ;
               }
               else
               {
                     int fib = // calculate recursively
                     memoized . put ( n , fib ) ;
                     return fib ;
               }
         }
    }
    

    You should be able to get decent (not optimal) performance out of this algorithm. The primary reason that the recursive fibonacci algorithm has horrible performance is b/c it is repeatedly calculating the same values. With recursion+memoization it never calculates any value more than once.

    Thanks to @Aristide for pointing out the subtle difference between memorization and memoization.

提交回复
热议问题