Recursive Fibonacci memoization

后端 未结 14 1437
走了就别回头了
走了就别回头了 2020-11-30 02:47

I need some help with a program I\'m writing for my Programming II class at universtiy. The question asks that one calculates the Fibonacci sequence using recursion. One mus

14条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 03:09

    public static int fib(int n, Map map){
    
        if(n ==0){
            return 0;
        }
    
        if(n ==1){
            return 1;
        }
    
        if(map.containsKey(n)){
            return map.get(n);
        }
    
        Integer fibForN = fib(n-1,map) + fib(n-2,map);
        map.put(n, fibForN);
    
        return fibForN; 
    
    }
    

    Similar to most solutions above but using a Map instead.

提交回复
热议问题