memoization for recursive Longest Increasing subsequence

偶尔善良 提交于 2020-01-24 12:10:07

问题


I came up with simple following recursive solution for Longest increasing sub-sequence. But, Can you help to include memoization into this recursive solution.

public int findLIS(int a[], int maxSoFar, int item, int count) {

        if(item == a.length) {
            return count;
        }
        int length1 = findLIS(a,maxSoFar, item+1, count);
        int length2 = 0;
        if(a[item] > maxSoFar) {

            length2 = findLIS(a, a[item], item+1, count + 1);
        }
        return Math.max(length1, length2);
}

PS: This not a homework question, it is more of my interest.


回答1:


Use a Map<Pair<Integer,Integer>,Integer>, and at the beginning of the method add:

Integer cache = map.get(new Pair<Integer,Integer>(maxSoFar,item));
if (cache != null) return cache;

Each time you return anything - make sure to write (maxSoFar,item)=returnValue to the map.

The idea is to map between the pair that represent where you are in the calculation - to the maximal value found for this state, to avoid recalculating it.


It seems java, so you can use apache commons Pair as your Pair interface.



来源:https://stackoverflow.com/questions/13781979/memoization-for-recursive-longest-increasing-subsequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!