简体   繁体   中英

How does recursive of number sum work in java?

I have this code for investigating of groupSum by using a recursive method. 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]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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