我正在尝试编写一个代码,将子集中的所有整数相加,看看它们是否加起来为零。这是我到目前为止所得到的
/**
* 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;
}
}
}
这是我收到的有关制作此代码的提示:
首先考虑集合的第一个元素,第一个元素和集合的其余部分是否存在零子集和?没有第一个和集合的其余部分,是否存在零子集和?如果 2 或 3 中的任何一个为真,则返回真,否则返回假
任何帮助,我一直在尝试一整天我无法让它为我的生活工作,在递归中我无法弄清楚如何自己调用该方法。
所以我的问题是我将如何在递归中编写这个方法?整个方法应该将子集的总和相加,看看它们是否等于零。