Alogrithm递归编码bat

时间:2018-06-28 12:58:56

标签: java algorithm recursion

递归2> groupSum6 http://codingbat.com/prob/p199368

我修改了第一个示例的解决方案,其中不存在使用6的条件。

下面的解决方案:

public boolean groupSum6(int start, int[] nums, int target) {
  // Base case: if there are no numbers left, then there is a
        // solution only if target is 0.
        if (start >= nums.length) return (target == 0);

        // Key idea: nums[start] is chosen or it is not.
        // Deal with nums[start], letting recursion
        // deal with all the rest of the array.

        // Recursive call trying the case that nums[start] is chosen --
        // subtract it from target in the call.
        if (nums[start] == 6) 
            return groupSum6(start + 1, nums, target - nums[start]);
        if (groupSum6(start + 1, nums, target - nums[start]))
            return true;

        // Recursive call trying the case that nums[start] is not chosen.
        if (groupSum6(start + 1, nums, target)) return true;

        // If neither of the above worked, it's not possible.
        return false;
}

但是当我更换时它不起作用

if (nums[start] == 6) 
                return groupSum6(start + 1, nums, target - nums[start]);

与:

if (nums[start] == 6) 
                groupSum6(start + 1, nums, target - nums[start]);

//注意:缺少返回语句。

然后,对于可能可以获取目标但不使用6的数组,算法将失败。例如,groupSum6(0,[5,6,2],7)期望值为false,但返回true。需要5 + 2,跳过6,但是必须按照说明使用每6。

我的问题是:'return'语句如何改变递归流程

1 个答案:

答案 0 :(得分:3)

因为javapass by reference,所以您在将参数传递给方法时没有传递实际的对象。您正在将引用传递给对象。因此,当您传递对对象的引用但取出返回调用时,该引用永远不会解析回变量,因此您实际上会丢弃递归调用的结果

尝试这个简单的程序,了解我的意思:

public static int foo(int x) {
    x++;
    if(x < 10) {
        foo(x);
    }
    return x;
}

如果我们调用System.out.println(foo(1));,则将打印出2,因为第一个x++得到了解决,但实际上您将所有递归调用的结果都丢弃了。

但是如果我们改变

if(x < 10) {
    foo(x);
}

收件人:

if(x < 10) {
    return foo(x);
}

结果将为10,因为我们return来自递归调用的结果