我需要编写一个获取4个参数的递归函数。如何管理递归函数?
第一个是数组。第二个 - 左指数,第三个是右指数和“K”指数。 “K”索引是一个数组中的单元格,lrft索引指向开始,右侧指向结尾。
一个数组可能包含诸如零和一的洋地黄。该方法返回包含单元格k的序列的最大长度。
在这里,我需要得到的结果的例子:
public static void main(String[] args) {
int[] A = {1,1,1,0,1,1,0,1,1,1,1,1,0,1,1};
System.out.println(floodOnes(A,0, A.length-1, 9)); // 5 output
System.out.println(floodOnes(A,0, A.length-1, 3)); // 0 output
System.out.println(floodOnes(A,0, A.length-1, 0)); // 3 output
System.out.println(floodOnes(A,0, A.length-1, 14)); // 2 output
}
public static int floodOnes(int [] A,int left, int right, int k){
//some logic
}
这是我实现:
public class Program {
public static void main(String[] args) {
int[] A = {1,1,1,0,1,1,0,1,1,1,1,1,0,1,1};
System.out.println(floodOnes(A,0,A.length-1, 9));
}
public static int floodOnes(int [] A,int left, int right, int k){
if (left != k) left+=1;
if (right != k) right-=1;
if (left == k && right == k) return A[k]; //condition when the recursive call stops
int res = floodOnes(A, left, right, k);
if (A[left] == 1 && A[right] == 1)
return res = A[left] + A[right]; //count ones
else return res;
}
}
但我的解决方案不能正常工作。
在这行:
if (A[left] == 1 && A[right] == 1)
return res = A[left] + A[right]; //count ones
如果条件之一isn`t执行一次,下面的收益不应附加产品造成的变量。
我不知道该怎么做。
*“写一个获取**三个**参数的递归函数”*然后继续用**四个**参数编写一个方法?那是怎么回事? – Andreas
'floodOnes(A,0,A.length-1 9)'是一个编译错误。请发布有效的代码,除非您询问编译错误。 – Andreas
@Andreas,它刚刚被编辑。 –