遞歸遞歸我試圖做一個代碼,添加一個子集中的所有整數,看看他們加起來爲零。這裏就是我有這麼遠申請子集總和
/**
* Solve the subset sum problem for a set of integer values.
*
* @param t
* a set of integer values
* @return <code>true</code> if there exists a non-empty subset of
* <code>t</code> whose elements sum to zero.
*/
public static boolean subsetSum(Set<Integer> t) {
return subsetSum(new ArrayList<Integer>(t), null);
}
/**
* Computes the sum of two Integers where one or both references are null. If
* both references are null then the result is null; otherwise the result is
* an integer equal to <code>a + b</code> where null references are treated as
* being equal to zero.
*
* @param a
* @param b
* @return the sum of <code>a</code> and <code>b</code>
*/
private static Integer add(Integer a, Integer b) {
if (a == null && b == null) {
return null;
} else if (a == null) {
return b;
} else if (b == null) {
return a;
}
return a + b;
}
/**
* Recursive solution for the subset sum problem.
*
* <p>
* <code>currentSum</code> holds the value of the subset under consideration;
* it should be <code>null</code> if the current subset is empty.
*
* @param t
* a list containing unique integer values (a set of integers)
* @param currentSum
* the current subset sum so far
* @return <code>true</code> if there exists a subset of <code>t</code> such
* that the sum of the elements in the subset and
* <code>currentSum</code> equals zero.
*/
******** THIS IS THE PART I HAD TO EDIT *************
private static boolean subsetSum(List<Integer> t, Integer currentSum) {
currentSum = 0;
for (int i = 0; i < t.size(); i++) {
currentSum = currentSum + (Integer)(t.get(i));
}
if (Lab9W.add(currentSum, t.get(0)) == 0) {
return true;
}
else if (Lab9W.add(currentSum, t.get(1)) == 0) {
return true;
} else if (Lab9W.add(-t.get(0),t.get(0)) == 0) {
return true;
}
else {
return false;
}
}
}
這裏有什麼提示,我已經收到有關使這個代碼:
consider the first element of the set first is there a subset sum of zero with first and the rest of the set? is there a subset sum of zero without first and the rest of the set? if either of 2 or 3 is true then return true, otherwise return false
任何幫助,請我一直在嘗試了一整天,我不能讓它開始工作對於我的生活,順利遞歸我不知道如何調用自己的方法。
所以我的問題是我將如何寫這種方法在遞歸?整個方法應該添加子集的總和,看它們是否等於零。
你試圖檢查的是數組中的第一個元素+所有元素的總和等於0? – 2013-03-26 01:25:07
是的,我是@JavaNewb原因那是什麼建議沒有? – callmealb 2013-03-26 01:27:56
你的整個邏輯根本沒有意義。我懷疑你是否真的明白了問題所在。假設在集合中有5個整數:a,b,c,d,e。如果任何這些整數總和爲0,你應該返回true。如果a + b + d == 0則返回true。你的邏輯根本沒有任何關聯。你只是將整個列表加起來,如果第一個/第二個元素(再次!)== 0或第一個元素的總和+值不爲空,那麼你返回true。這個邏輯的重點是什麼? – 2013-03-26 01:55:42