这是一个更正的工作解决方案,有两个基于@Mattew Pape 答案的示例。但这是尝试所有可能分区的蛮力方法。这个可以进一步优化。这个方法的复杂度是O(N!)。
public class partitonArray {
static int total = 0;
public static int countWays(int [] arr) {
int sum = 0;
for (int index = 0; index < arr.length; ++index) {
sum += arr[index];
List<List<Integer>> lst = new ArrayList();
List<Integer> l1 = new ArrayList();
for(int j=0;j<=index;j++)
l1.add(arr[j]);
lst.add(l1);
recursiveCount(sum, Arrays.copyOfRange(arr, index + 1, arr.length), lst);
}
return total;
}
public static void recursiveCount(int partitionSum, int [] remaining, List<List<Integer>> lst) {
// base case
if (remaining.length == 0 && lst.size() > 1) {
System.out.println("Result here = "+lst.toString());
total++;
}
int sum = 0;
List<Integer> l1 = new ArrayList();
for (int index = 0; index < remaining.length; ++index) {
sum += remaining[index];
l1.add(remaining[index]);
// did we hit the mark?
if (sum == partitionSum) {
// make a partion here and see if we can finish the rest of the array
lst.add(l1);
recursiveCount(partitionSum, Arrays.copyOfRange(remaining, index + 1, remaining.length), lst);
lst.remove(l1);
}
}
}
public static void main(String [] args) {
//int [] arr ={ 2, 4, 6,7, 7, 6, 3, 3, 3, 4, 3, 4,5, 4, 4, 3, 3, 1,4};
int [] arr = {1, 2, 3, 0, 3};
System.out.println(countWays(arr));
}
}
**Output**:
Result here = [[1, 2], [3], [0, 3]]
Result here = [[1, 2], [3, 0], [3]]
2
/*
Result here `enter code here`= [[2, 4, 6, 7], [7, 6, 3, 3], [3, 4, 3, 4, 5], [4, 4, 3, 3, 1, 4]]
Result here = [[2, 4, 6, 7, 7, 6, 3, 3], [3, 4, 3, 4, 5, 4, 4, 3, 3, 1, 4]]
2
*/