Recursive Fibonacci memoization

后端 未结 14 1439
走了就别回头了
走了就别回头了 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:31

    I believe you forget to actually look up stuff in your dictionary.

    Change

    else
        return dictionary[n] = fibonacci(n-1) + fibonacci(n-2);
    

    to

    else {
        if (dictionary[n] > 0)
            return dictionary[n];
    
        return dictionary[n] = fibonacci(n - 1) + fibonacci(n - 2);
    }
    

    and it works just fine (tested it myself :)

提交回复
热议问题