<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:
    // traverse
    // first calculate the target sum of each subsets
    // if cannot evenly divide, return false
    // or when the biggest value > target
    // then dfs to find k such subsets
    // potentially many ways to prune
    // 1. start form biggest value
    // 2. 
    // when dfs, record how many subsets has been found
    // or --k if found a valid subsets
    // base case: k == 0 or used up all nums
    // record nums remain, may be ...
    // backtracking
    // each time select any one num from the remaining nums
    // and dfs further
    // we can use a visite array or we can set nums[i] == -1 if used
    // remember to cache nums[i] and turned it back
    bool canPartitionKSubsets(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end(), greater<int>());
        const int total = accumulate(nums.begin(), nums.end(), 0);
        const int maxNum = *max_element(nums.begin(), nums.end());
        const int target = total / k;
        if (total % k != 0 || maxNum > target)
            return false;
        int bitMask = 0;
        unordered_map<int, bool> memo;
        return partition(nums, k, target, 0, bitMask, memo);
    }

private:
    bool partition(vector<int>& nums, int k, int target, int currSetSum, int& mask, unordered_map<int, bool>& memo) {
        if (currSetSum == target) {
            currSetSum = 0;
            if (--k == 0) {
                memo[mask] = true;
                return memo[mask];
            }
        }
        if (currSetSum > target) {
            memo[mask] = false;
            return memo[mask];
        }
        if (memo.contains(mask))
            return memo[mask];

        for (int i = 0; i < nums.size(); ++i) {
            if (mask & (1 << i))  // used
                continue;
            mask |= (1 << i);
            if (partition(nums, k, target, currSetSum + nums[i], mask, memo)) {
                memo[mask] = true;
                return memo[mask];
            }
            mask ^= (1 << i);
        }
        memo[mask] = false;
        return memo[mask];
    }
};
35675