805. Split Array With Same Average

In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)

Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.

 

Example :
Input: 
[1,2,3,4,5,6,7,8]
Output: true
Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.

 

Note:

  • The length of A will be in the range [1, 30].
  • A[i] will be in the range of [0, 10000].

 

Approach #1: DP. [Java]

class Solution {
    public boolean splitArraySameAverage(int[] A) {
        int sum = 0;
        for (int num : A) {
            sum += num;
        }
        
        boolean[][] dp = new boolean[sum+1][A.length/2+1];
        dp[0][0] = true;
        
        for (int num : A) {
            for (int i = sum; i >= num; --i) {
                for (int j = 1; j <= A.length/2; ++j) {
                    dp[i][j] = dp[i][j] || dp[i-num][j-1];
                }
            }
        }
        
        for (int i = 1; i <= A.length/2; ++i)
            if (sum * i % A.length == 0 && dp[sum * i / A.length][i])
                return true;
        
        return false;
    }
}

  

 

Approach #2: DFS. [Java]

class Solution {    
    public boolean check(int[] A, int leftSum, int leftNum, int startIndex) {       
        if (leftNum == 0) return leftSum == 0;
        if ((A[startIndex]) > leftSum / leftNum) return false;
        for (int i = startIndex; i < A.length - leftNum + 1; i ++) {
	    if (i > startIndex && A[i] == A[i - 1]) continue;
            if (check(A, leftSum - A[i], leftNum - 1, i + 1)) return true;
        }
        return false;       
    }
    
    public boolean splitArraySameAverage(int[] A) {
        if (A.length == 1) return false;
        int sumA = 0;
        for (int a: A) sumA += a;
        Arrays.sort(A);
        for (int lenOfB = 1; lenOfB <= A.length / 2; lenOfB ++) {
            if ((sumA * lenOfB) % A.length == 0) {
                if (check(A, (sumA * lenOfB) / A.length, lenOfB, 0)) return true;
            }
        }
        return false;
        
    }
}

  

Analysis:

Can't understanding.

 

posted @ 2019-05-17 20:56  Veritas_des_Liberty  阅读(178)  评论(0编辑  收藏  举报