<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>

#include <vector>
#include <numeric>
#include <algorithm>
#include <unordered_map>

using namespace std;

class Solution {
    unordered_map<int, bool> memo;  // Memoization cache
    
    bool rec(vector<int>& arr, int pos, int k, int cur_sum, int target_sum, int mask, int n) {
        // If we've filled k-1 subsets correctly, the last subset must also be correct
        if (k == 1) return true;
        
        // If the current subset has reached the target sum, start filling the next subset
        if (cur_sum == target_sum) {
            return rec(arr, 0, k - 1, 0, target_sum, mask, n);
        }
        
        // Check the memo cache
        if (memo.count(mask)) return memo[mask];
        
        for (int i = pos; i < n; ++i) {
            // If the current number is not used (check using bitmask) and it doesn't exceed the remaining sum
            if (!(mask & (1 << i)) && cur_sum + arr[i] <= target_sum) {
                // Mark the current number as used (set the bit in the mask)
                if (rec(arr, i + 1, k, cur_sum + arr[i], target_sum, mask | (1 << i), n)) {
                    return memo[mask] = true;
                }
            }
        }
        
        return memo[mask] = false;
    }
    
public:
    bool canPartitionKSubsets(vector<int>& nums, int k) {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        if (sum % k != 0) return false;

        int target_sum = sum / k;
        int n = nums.size();
        sort(nums.rbegin(), nums.rend());  // Sort in descending order for optimization
        
        // Start recursion with the memoization cache
        return rec(nums, 0, k, 0, target_sum, 0, n);
    }
};

30619