【发布时间】: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