【问题标题】:Memoization of this leetcode problem. How do I memoize this recursive solution这个 leetcode 问题的记忆。我如何记住这个递归解决方案
【发布时间】:2020-12-21 12:19:55
【问题描述】:

我已经完成了所有可能的滑动,最后我通过了数组以检查它是否增加。 这是question,我写的递归方法如下

class Solution {
    public int minSwap(int[] A, int[] B) {
        
        return helper(A,B,0,0);
    }
    
    boolean helper2(int[] A,int[] B){
        
        for(int i=0;i<A.length-1;i++){
           if(A[i]>=A[i+1] || B[i]>=B[i+1])
               return false;
        }
        return true;
        
    }
    
    int helper(int[] A,int[] B,int i,int swaps){
        if(i==A.length && helper2(A,B)==true)
            return swaps;
        if(i==A.length)
            return 1000;
       
        
        swap(A,B,i);
       int c=helper(A,B,i+1,swaps+1);
        swap(A,B,i);
        int b=helper(A,B,i+1,swaps);
        
        
      return Math.min(b,c); 
    }
    private void swap(int[] A, int[] B, int index){
        int temp = A[index];
        A[index] = B[index];
        B[index] = temp;
    }
    
}

在这里,我尝试了所有可能的滑动,然后检查它们并以最少的滑动返回一个。我该如何做这个记忆。我应该在这段代码的记忆中使用哪些变量。有没有选择记忆变量的经验法则?

【问题讨论】:

    标签: java dynamic-programming memoization


    【解决方案1】:

    Wikipedia 说:

    在计算中,记忆化或记忆化是一种优化技术,主要用于通过存储昂贵的函数调用的结果返回缓存的结果来加速计算机程序,当同样的输入再次出现。

    由于AB 不变,输入为iswaps,因此对于两者的每一种组合,我们都需要存储结果。

    执行此操作的一种方法是使用 HashMap 和具有 2 个值的键,例如

    class Key {
        int i;
        int swaps;
        // implement methods, especially equals() and hashCode()
    }
    

    然后您可以在helper() 的开头添加以下内容,但您可能希望在两个if 语句之后添加它:

    Key key = new Key(i, swap);
    Integer cachedResult = cache.get(key);
    if (cachedResult != null)
        return cachedResult;
    

    然后将return 语句替换为:

    int result = Math.min(b,c);
    cache.put(key, result);
    return result;
    

    cache 是字段还是传递的参数完全取决于您。

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      相关资源
      最近更新 更多