I want to find the subsets of a set of integers. It is the first step of "Sum of Subsets" algorithm with backtracking. I have written the following code, but it doesn't return the correct answer:
BTSum(0, nums);
///**************
ArrayList<Integer> list = new ArrayList<Integer>();
public static ArrayList<Integer> BTSum(int n, ArrayList<Integer> numbers) {
if (n == numbers.size()) {
for (Integer integer : list) {
System.out.print(integer+", ");
}
System.out.println("********************");
list.removeAll(list);
System.out.println();
} else {
for (int i = n; i < numbers.size(); i++) {
if (i == numbers.size() - 1) {
list.add(numbers.get(i));
BTSum(i + 1, numbers);
} else {
list.add(numbers.get(i));
for (int j = i+1; j < numbers.size(); j++)
BTSum(j, numbers);
}
}
}
return null;
}
For example, if I want to calculate the subsets of set = {1, 3, 5}
The result of my method is:
1, 3, 5, ********************
5, ********************
3, 5, ********************
5, ********************
3, 5, ********************
5, ********************
I want it to produce:
1, 3, 5
1, 5
3, 5
5
I think the problem is from the part
list.removeAll(list);
but I dont know how to correct it.
question from:
https://stackoverflow.com/questions/4640034/calculating-all-of-the-subsets-of-a-set-of-numbers 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…