2014-03-03 36 views
1

我有這樣的情況下,對於輸入的工作原理:遞歸添加subet

{-5,0,5}, 2, 0 // which correctly evaluates to true 
{-5,0,5}, 3, 4 // which correctly evaluates to false 
{-5,0,5}, 3, 0 // which correctly evaluates to true 

但隨着輸入:

{6,5,6}, 2, 12 // says false when true 

它不會給出正確的布爾值... 燦有人幫助調試問題?

public static boolean subset(int[] array, int n, int target) { 
    for (int i = 0; i < array.length; i++) { 
     int[] list = new int[array.length - 1]; 

     for (int j = 0; j < array.length - 1; j++) { 
      list[j] = array[j+1]; 
     } 
     subset(list, n, target); 
    } 

    int sum = 0; 
    for (int i = 0; i < array.length; i++) { 
     sum += array[i]; 
    } 

    if (sum == target) { 
     return true; 
    } 
    else { 
     return false; 
    } 
} 
+3

如果您告訴我們該方法應該完成什麼,這將有所幫助。 – ajb

回答

0

不知道你在計算什麼,但我懷疑你的問題在於子集(list,n,target)的遞歸調用。你沒有改變一個對象,你忽略了返回值。 另外:根本沒有使用變量「n」。

0

你對遞歸的返回值什麼都不做。

這條線:

subset(list, n, target); 

應改爲:

if (subset(list, n, target)){ 
    return true; 
} 

而且,你沒有做任何事情與你n可變


我喜歡你正在努力男人,所以我會讓你更容易:)。

public static void main(String[] args) { 
    int[] array = {1, 2, 3, 4, 5}; 
    int n = 3; 
    int sum = 10; 
    System.out.println(subset(array, n, sum)); 
} 

public static boolean subset(int[] array, int n, int sum) { 
    //If I have enough numbers in my subarray, I can check, if it is equal to my sum 
    if (array.length == n) { 
     //If it is equal, I found subarray I was looking for 
     if (addArrayInt(array) == sum) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    //Trying all possibilites and doing recursion 
    for (int i = 0; i < array.length; i++) { 
     //if some recursion returned true, I found it, so I can also return true 
     int[] subarray = new int[array.length - 1]; 
     int k = 0; 
     for (int j = 0; j < subarray.length; j++) { 
      if (i == j) { 
       k++; 
      } 
      subarray[j] = array[j + k]; 
     } 
     if (subset(subarray, n, sum)) { 
      return true; 
     } 
    } 

    //If I didnt find anything, I have to return false 
    return false; 
} 

public static int addArrayInt(int[] array) { 
    int res = 0; 
    for (int i = 0; i < array.length; i++) { 
     res += array[i]; 
    } 
    return res; 
} 

但是,你不明白遞歸的基本知識,你很接近,但我認爲你錯過了主要想法:)。我建議你嘗試遞歸計算Factorial,然後嘗試Fibonacci,它可以提供幫助,並且在互聯網上有教程。

+0

有沒有辦法做到這一點,同時保持方法的原始簽名? – user3362954

+0

什麼是「簽名」? – libik

+0

@ user3362954 - 相同的參數,對吧?那麼這是可能的,請看編輯代碼 – libik