记住这个 leetcode 问题。我如何记住这个递归解决方案

时间:2020-12-21 12:19:55

标签: java dynamic-programming memoization

我已经完成了所有可能的滑动,然后最后我通过了要检查的数组是否在增加。 这是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;
    }
    
}

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

1 个答案:

答案 0 :(得分:0)

Wikipedia 说:

<块引用>

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

由于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 是传递的字段还是参数完全取决于您。