【问题标题】:memoization for recursive Longest Increasing subsequence递归最长递增子序列的记忆
【发布时间】:2012-11-26 17:55:01
【问题描述】:

我为最长递增子序列提出了简单的以下递归解决方案。 但是,您能帮忙将记忆功能包含在这个递归解决方案中吗?

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:这不是作业问题,这更符合我的兴趣。

【问题讨论】:

  • Java,但您可以轻松转换为您喜欢的语言。如果你愿意,我可以为你做

标签: algorithm dynamic-programming memoization


【解决方案1】:

使用Map<Pair<Integer,Integer>,Integer>,并在方法的开头添加:

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

每次您return 时,请务必将(maxSoFar,item)=returnValue 写入地图。

这个想法是在代表您在计算中的位置的对之间映射到为该状态找到的最大值,以避免重新计算它。


好像是java,所以你可以使用apache commons Pair作为你的Pair接口。

【讨论】:

  • 谢谢。在此处发布之前,我快速检查了一个数组 { 10, 22, 9, 33, 21, 50, 41, 60, 80 };和一个备忘录 = new int[10][81];但是,它对我不起作用。我也会检查您的解决方案。
  • @coder000001:相当于地图解法。请发布您使用的代码,其中可能存在错误
  • 它可能不等价。当数组变大时,分配内存可能会导致核心转储。所以地图是一个更好的解决方案。
  • 这里是使用地图pastebin.com/BZatp7by的实现,以防有人感兴趣。
猜你喜欢
  • 2017-07-10
  • 2020-06-28
  • 2016-05-29
  • 2021-12-04
  • 2013-07-03
  • 2012-09-19
相关资源
最近更新 更多