<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> if it is possible to divide this array into <code>k</code> non-empty subsets whose sums are all equal.</p>

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

<pre>
<strong>Input:</strong> nums = [4,3,2,3,5,2,1], k = 4
<strong>Output:</strong> true
<strong>Explanation:</strong> It is possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
</pre>

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

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

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

<ul>
	<li><code>1 &lt;= k &lt;= nums.length &lt;= 16</code></li>
	<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
	<li>The frequency of each element is in the range <code>[1, 4]</code>.</li>
</ul>

class Solution {
public:
    bool solve(std::vector<int> &nums, int k, int n, int curSum, int mask, int target, std::vector<int> &dpTable) {
        if (mask == (1 << n) - 1) return true;

        if (dpTable[mask] != -1) return dpTable[mask];

        bool result = false;
        for (int i = 0; i < n; ++i) {            
            if (nums[i] + curSum > target) break;
            if ((mask & (1 << i))) continue;

            result |= solve(nums, k, n, (curSum + nums[i]) % target, mask | (1 << i), target, dpTable);
        }
        return dpTable[mask] = result;
    }
    bool canPartitionKSubsets(vector<int>& nums, int k) {
        int n = static_cast<int>(nums.size());
        int total = std::accumulate(nums.begin(), nums.end(), 0);
        if (total % k != 0) return false;

        int target = total / k;
        std::sort(nums.begin(), nums.end());
        if (nums.back() > target) return false;

        std::vector<int> dpTable(1 << n, -1);
        return solve(nums, k, n, 0, 0, target, dpTable);
    }
};
21518