Having some trouble with this recursive backtracking problem:
"Write a method partitionable that accepts a list of integers as a parameter and uses recursive backtracking to discover whether the list can be partitioned into two sub-lists of equal sum. Your method should return true if the given list can be partitioned equally, and false if not."
For example, the list [1, 2, 3] can be partitioned into the sublists [1, 2] and [3], so it would produce a result of "true."
My solution seems correct, but returns false no matter what. I don't understand why.
public static boolean partitionable(List<Integer> list1) {
List<Integer> list2 = new ArrayList<Integer>();
return partitionable(list1, list2);
}
public static boolean partitionable(List<Integer> list1, List<Integer> list2) {
boolean finalAnswer = false;
int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < list1.size(); i++) {
sum1 += list1.get(i);
}
for (int i = 0; i < list2.size(); i++) {
sum2 += list2.get(i);
}
if (sum1 == sum2) {
return true;
} else {
for (int i = 0; i < list1.size() - 1; i++) {
int number = list1.remove(i);
list2.add(number);
finalAnswer = partitionable(list1, list2);
list2.remove(list2.size() - 1);
list1.add(i, number);
}
}
return finalAnswer;
}
EDIT: I fixed the problem of removing the element from list1 twice.