簡體   English   中英

數字總和的遞歸如何在java中工作?

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

我有使用遞歸方法調查 groupSum 的代碼。 我不明白這個例子中的遞歸是如何工作的。 我使用了調試,但仍然不明白。

   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);
    }

}

謝謝

有兩個遞歸調用

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

如果我們減去nums[start]處的值,嘗試看看我們是否可以達到剩余的目標

或者我們可以在沒有這個數字的情況下達到目標。

groupSum( start+1, nums,  target);

如果調試器沒有幫助您可以添加調試語句

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);
}

印刷

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

你可以看到它嘗試了所有剩下-4的值,然后它返回並嘗試不包括8 ,然后嘗試不包括4 ,結果證明是成功的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM