2016-04-23 19 views
2

我有通過使用遞歸方法調查groupSum的代碼。 我不明白遞歸在這個例子中是如何工作的。我用調試,但仍然不明白。數量和的遞歸如何在java中工作?

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

} 

感謝

+0

不說你發現混淆,它很難知道你不明白。使用調試器應該能夠提供幫助,而且使用越多,它就會有用。 (它帶有練習) –

+0

http://codingbat.com/prob/p145416上有一個很好的對這個問題的處理。你使用相同的測試用例。你從那裏來過嗎?他們的解釋怎麼樣,你不明白? –

+0

是的,我來自那裏..我沒有正確理解這一行'groupSum(start + 1,nums,target-nums [start])' –

回答

2

有兩個遞歸調用

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,結果證明是成功的。

+0

謝謝...我們可以寫這個'groupSum(start + 1,nums ,target-nums [start])'以另一種方式? –

+0

@DfgfHgh您可以更改簽名以使其更清晰一些。如果調試器不能幫助您,我建議在開始時在每個調用中打印輸入。 –

+0

@DfgfHgh我已經更新了我的答案,以包含調試日誌記錄。 –