简体   繁体   English

数字总和的递归如何在java中工作?

[英]How does recursive of number sum work in java?

I have this code for investigating of groupSum by using a recursive method.我有使用递归方法调查 groupSum 的代码。 I do not understand how the recursive works in this example.我不明白这个例子中的递归是如何工作的。 I used debug but still do not understand it.我使用了调试,但仍然不明白。

   public class test {

    public boolean groupSum(int start, int[] nums, int target) {

        if(target == 0) 
            return true;
        if (start == nums.length)
             return false;
        if (groupSum( start+1, nums,  target-nums[start])) // what is the meaning of this line ? can we change this line to make the code easier to understand ?
            return true;
        return groupSum( start+1, nums,  target);

    }


    public static void main(String[] args) {

        int x = 0;
        int y [] = {2,4,8};
        int k = 10;

        test t = new test();
        boolean result = t.groupSum(x,y,k);
        System.out.println(result);
    }

}

Thanks谢谢

There is two recursive calls有两个递归调用

groupSum( start+1, nums,  target-nums[start])

try to see if we can reach the remaining target if we subtract the value at nums[start]如果我们减去nums[start]处的值,尝试看看我们是否可以达到剩余的目标

or can we reach the target without this number.或者我们可以在没有这个数字的情况下达到目标。

groupSum( start+1, nums,  target);

It the debugger doesn't help you can add debugging statements如果调试器没有帮助您可以添加调试语句

public static void main(String[] args) {
    int x = 0;
    int[] y = {2, 4, 8};
    int k = 10;

    boolean result = groupSum(x, y, k);
    System.out.println(result);
}

public static boolean groupSum(int start, int[] nums, int target) {
    System.out.println("groupSum(" + start + ", " + Arrays.toString(nums) + ", " + target + ")");
    if (target == 0)
        return true;
    if (start == nums.length)
        return false;
    if (groupSum(start + 1, nums, target - nums[start]))
        return true;
    System.out.print("or ");
    return groupSum(start + 1, nums, target);
}

prints印刷

groupSum(0, [2, 4, 8], 10)
groupSum(1, [2, 4, 8], 8)
groupSum(2, [2, 4, 8], 4)
groupSum(3, [2, 4, 8], -4)
or groupSum(3, [2, 4, 8], 4)
or groupSum(2, [2, 4, 8], 8)
groupSum(3, [2, 4, 8], 0)
true

You can see it tried all all the values which left -4 then it went back and tried not including 8 , and then it tried not including 4 which turned out to be successful.你可以看到它尝试了所有剩下-4的值,然后它返回并尝试不包括8 ,然后尝试不包括4 ,结果证明是成功的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM