<p>You are given an integer array <code>nums</code>.</p>

<p>You should move each element of <code>nums</code> into one of the two arrays <code>A</code> and <code>B</code> such that <code>A</code> and <code>B</code> are non-empty, and <code>average(A) == average(B)</code>.</p>

<p>Return <code>true</code> if it is possible to achieve that and <code>false</code> otherwise.</p>

<p><strong>Note</strong> that for an array <code>arr</code>, <code>average(arr)</code> is the sum of all the elements of <code>arr</code> over the length of <code>arr</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,4,5,6,7,8]
<strong>Output:</strong> true
<strong>Explanation:</strong> We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [3,1]
<strong>Output:</strong> false
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 30</code></li>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution {
public:
    unordered_map<string, int> mp;

    bool helper(vector<int>& nums, int i, int n, int sum, int n1) {
        if (n1 == 0)
            return sum == 0;
        if (i == n)
            return false;
        string key = to_string(i) + "#" + to_string(n1) + "#" + to_string(sum);
        if (mp.count(key))
            return mp[key];

        if (nums[i] <= sum) {
            return mp[key] = helper(nums, i + 1, n, sum - nums[i], n1 - 1) ||
                             helper(nums, i + 1, n, sum, n1);
        } else
            return mp[key] = helper(nums, i + 1, n, sum, n1);
    }

    bool splitArraySameAverage(vector<int>& nums) {
        /*
        Let's try to see what happens when an answer exists.
        Assume we split the array A into B and C so that avg(B) == avg(C).
        It follows that avg(B) == avg(C) == avg(A)
        So we only need to find a proper subset B such that avg(B) == avg(A) and
        we can just put the remaining elements in C. Now if avg(B)==avg(A), that
        means sum(B) /B.length == sum(A) / N or, sum(B) == sum(A) * B.length / N
        */
        int sum = accumulate(nums.begin(), nums.end(), 0ll);
        int n = nums.size();
        vector<vector<vector<bool>>> dp(
            n, vector<vector<bool>>(n + 1, vector<bool>(sum + 1, false)));
        for (int i = 1; i < n; i++) {
            if ((sum * i) % n == 0) {
                int req_sum = (sum * i) / n;
                if (helper(nums, 0, n, req_sum, i))
                    return true;
            }
        }
        return false;
    }
};
291381