【问题标题】:Trouble with a recursive method递归方法的问题
【发布时间】:2017-12-24 22:29:40
【问题描述】:
public static boolean array6(int[] nums, int index) {
if(nums.length > index+1)
{
if(nums[index] == 6)
return true;
else
array6(nums,index+1);
}
else if(nums.length==index+1)
{
if(nums[index] == 6)
return true;
else
return false;
}
return false;
}
作为我的 CSA 课程练习的一部分,我们必须编写一个方法来查找 6 是否存在于 int 数组中并返回相应的布尔值。如果数组中的第一个数字是 6,我编写的方法有效,但否则无效。为什么?
注意:必须递归完成
【问题讨论】:
标签:
java
arrays
recursion
【解决方案1】:
问题是您没有触发递归,因为在您的代码中没有任何地方返回方法本身的结果。如果条件为true,则重写if statement 的内容,如下所示将使其按预期工作:
if (nums.length > index_next)
{
if (nums[index] == 6)
return true;
// you have to return the result of the function here
// in order to obtain an effective recursion, otherwise the
// method is called but it's output value is ignored and the
// functions goes outside the scope of the if statement
// reaching the "return false" located at the bottom
return array6(nums, index_next);
}
但总的来说,您的函数包含很多问题。您的任务非常简单,但是您正在以极其复杂的方式对其进行编码。您可以使用许多内置函数来实现相同的结果......即使您不想使用它们,一个简单的for loop 也可以完成这项工作:
boolean found = false;
for (int i = 0; i < nums.length; ++i)
{
if (nums[i] == 6)
{
found = true;
break;
}
}
编辑:递归实现
public static boolean array6(int[] nums, int index)
{
if (index == nums.length)
return false;
if (nums[index] == 6)
return true;
return array6(nums, index + 1);
}
【解决方案2】:
一个紧凑的解决方案
bool array6(int* array, int len, int index) {
if (index == len) {
return false;
}
return array[index] == 6 || array6(array, len, index + 1);
}