类似这样的解决方案应该能解决您的问题并处理所有情况。
public static boolean canBeDividedEqually(int[] arr) {
if (arr.length % 2 != 0) {
return false;
}
int sum = getSum(arr);
if (sum % 2 != 0) {
return false;
}
return canBeDividedEqually(arr, sum);
}
public static int getSum(int[] arr) {
return getSum(arr, 0, 0);
}
private static int getSum(int[] arr, int sum, int index) {
if (index >= arr.length) {
return sum;
}
return getSum(arr, sum + arr[index], index + 1);
}
private static boolean canBeDividedEqually(int[] arr, int sum) {
return canBeDividedEqually(arr, sum/2, 0, arr.length/2, 0, 0);
}
private static boolean canBeDividedEqually (int[] arr, int searchSum, int currentSum, int searchQuantity, int currentQuantity, int nextIndex) {
if(searchSum == currentSum && searchQuantity == currentQuantity) {
return true;
}
if(searchSum <= currentSum || searchQuantity <= currentQuantity) {
return false;
}
if(nextIndex + (searchQuantity - currentQuantity) > arr.length) {
return false;
}
if(canBeDividedEqually(arr, searchSum, currentSum + arr[nextIndex], searchQuantity, currentQuantity + 1, nextIndex + 1)) {
System.out.println("true");
return true;
}
return canBeDividedEqually(arr, searchSum, currentSum, searchQuantity, currentQuantity, nextIndex + 1);
}