<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:
  void gen(const vector<int>& a, int n, int i, int k, int sum, set<pair<int,int>>& res) {
    if (i == n) {
      res.insert({ k, sum });
      // cout << k << " "<< sum << endl;
      return;
    }
    
    gen(a, n, i+1, k, sum, res);
    gen(a, n, i+1, k+1, sum+a[i], res);
  }
  
  set<pair<int,int>> genSubsetSum(const vector<int>& a, int n) {
    set<pair<int,int>> res;
    gen(a, n, 0, 0, 0, res);
    return res;
  }
  
  bool splitArraySameAverage(vector<int>& nums) {
    if ((int) nums.size() == 1) return false;
    
    int sum = 0;
    for (int x : nums) sum += x;
    // average = sum / n
    
    vector<int> a, b;
    for (int x : nums) {
      if (a.size() <= b.size()) a.push_back(x);
      else b.push_back(x);
    }
    
    int m = a.size(), n = b.size();
    
    auto sa = genSubsetSum(a, m);
    auto sb = genSubsetSum(b, n);
    
    for (int size_left = 1; size_left < (int) nums.size(); ++size_left) {
      if ((sum * size_left) % (int) nums.size() != 0) continue;
      
      int sum_left = sum * size_left / (int) nums.size();
      
      // cout << size_left << " " << sum_left << " ?" << endl;
      
      // Can we construct sum_left, size_left?
      for (auto& [k, v] : sa) if (k <= size_left && v <= sum_left && sb.count({ size_left - k, sum_left - v}) > 0) {
        return true;
      }
    }
    
    return false;
  }
};
36016