How can a recursive Java method be memoized?

后端 未结 2 1026
忘掉有多难
忘掉有多难 2020-12-19 13:40

So I\'ve built this program to build different stair cases. Essentially the problem is: Given an integer N, how many different ways can you build the staircase. N is guarant

2条回答
  •  我在风中等你
    2020-12-19 13:57

    Use a small class to hold the pairs (height, bricks), say:

    private static class Stairs {
        private int height;
        private int bricks;
        Stairs(int height, int bricks) {
            this.height = height; this.bricks = bricks;
        }
    }
    

    Then use a global HashMap, initialized in the main():

    map = new HashMap();
    

    In the bricks() function, check if the solution for a particular (height, bricks) pair is in the map. If yes, just return it from the map via a call to the get() method. Otherwise, do the computation:

    Stairs stairsObj = new Stairs(height, bricks);
    if(map.get(stairsObj) == null) {
        // Put your compute code here
    }
    

    Before every return statement in the function, add two additional statements. Something like:

    int result = ;
    map.put(stairsObj, result);
    return result;
    

提交回复
热议问题