How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?

前端 未结 22 1091
一生所求
一生所求 2020-12-02 11:20

How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

22条回答
  •  广开言路
    2020-12-02 11:57

    Found solution here

    package sort;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class ArraySumSplit {
    
    public static void main (String[] args) throws Exception {
    
        int arr[] = {1 , 2 , 3 , 4 , 5 , 5, 1, 1, 3, 2, 1};
        split(arr);
    
    }
    
    static void split(int[] array) throws Exception {
        int sum = 0;
        for(int n : array) sum += n;
        if(sum % 2 == 1) throw new Exception(); //impossible to split evenly
        List firstPart = new ArrayList();
        List secondPart = new ArrayList();
        if(!dfs(0, sum / 2, array, firstPart, secondPart)) throw new Exception(); // impossible to split evenly;
        //firstPart and secondPart have the grouped elements, print or return them if necessary.
        System.out.print(firstPart.toString());
        int sum1 = 0;
        for (Integer val : firstPart) {
            sum1 += val;
        }
        System.out.println(" = " + sum1);
    
        System.out.print(secondPart.toString());
        int sum2 = 0;
        for (Integer val : secondPart) {
            sum2 += val;
        }
        System.out.println(" = " + sum2);
    }
    
    static boolean dfs(int i, int limit, int[] array, List firstPart, List secondPart) {
        if( limit == 0) {
            for(int j = i; j < array.length; j++) {
                secondPart.add(array[j]);
            }
            return true;
        }
        if(limit < 0 || i == array.length) {
            return false;
        }
        firstPart.add(array[i]);
        if(dfs(i + 1, limit - array[i], array, firstPart, secondPart)) return true;
        firstPart.remove(firstPart.size() - 1);
    
        secondPart.add(array[i]);
        if(dfs(i + 1, limit, array, firstPart, secondPart)) return true;
        secondPart.remove(secondPart.size() - 1);
        return false;
    }
    }
    

提交回复
热议问题