我试图找出是否存在其总和等于目标的子集然后打印它。我是java的新手,有时候递归有点令人困惑
void sumOfSubsets(int n, int[] w, int W) {
if (W == 0)
return;
if ((W < 0) || (n < 0))
return;
if (W == 0) {
System.out.print(w[n] + " ");
return;
}
sumOfSubsets(n - 1, w, W);
}
答案 0 :(得分:0)
一般来说,如果你问自己,递归变得不那么混乱了:
在你的情况下答案是:
将这些答案翻译成代码:
boolean hasSumEqualTo(List<Integer> list, int sum) {
if (list.isEmpty())
return sum == 0;
int first = list.remove(0);
return hasSumEqualTo(list, sum) || hasSumEqualTo(list, sum - first);
}
或者,使用数组:
boolean hasSumEqualTo(int i, int[] list, int sum) {
if (i == list.length)
return sum == 0;
return hasSumEqualTo(i + 1, list, sum) || hasSumEqualTo(i + 1, list, sum - list[i]);
}
如果您只想打印所有子集:
void printSubsetsThatSumTo(String current, List<Integer> list, int sum) {
if (list.isEmpty()) {
if (sum == 0)
System.out.println(current);
} else {
int first = list.remove(0);
printSubsetsThatSumTo(current, list, sum);
printSubsetsThatSumTo(current + " " + first, list, sum - first);
}
}
在所有情况下,模式完全相同。