1

I have a quick question about implementing the Fibonacci sequence using the memoization (DP). I am using a HashTable, but for some reason, the table never seems to contain the elements. I inserted a print statement to print out something whenever a value was read from the hashtable and it seems like this never happens. I feel like its a simple fix, but I don't see it.

  public static int getFib(int n) {
        HashMap<Integer, Integer> dictionary = new HashMap<Integer, Integer>();
        if (n <= 2)
            return 1;
        else if (dictionary.containsKey(n)) {
            System.out.println("Reading From Table");
            return dictionary.get(n);
        } else {
            int val = getFib(n - 1) + getFib(n - 2);
            dictionary.put(n, val);
            return val;
        }
    }
2
  • 4
    'memoization', not 'memorization'. Commented Jan 1, 2015 at 4:53
  • (-/ Starts with double colon, double negation and no continuous form in the title /-). Pertaining to code: in declarations, prefer interfaces over implementations. Avoid one hit on the Map: use a variable result = dictionary.get(n); if (null != result) … Commented Jan 1, 2015 at 9:37

4 Answers 4

5

You're calling getFib() recursively, and instantiating a new dictionary with each call. Make the dictionary a class-level variable.

Sign up to request clarification or add additional context in comments.

Comments

4

dictionary is a local variable so the scope of this variable is within the function getFib.

If you call the function getFib recursively then each time the hash map will be created and instantiated and the scope of the hashmap dictionary will end on returning from the function.

You can have a global variable instead to solve this problem.

Comments

3

Initialize the dictionary outside your method. Right now, you are creating a new 'dictionary' in each recursive call.

Comments

2

Make the dictionary a member variable rather than a local variable

private HashMap<Integer, Integer> dictionary = new HashMap<Integer, Integer>();

public static int getFib(int n) {

    // some operations
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.