<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:
    def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
        N = len(nums)
        S = sum(nums)
        if S % k != 0: 
            return False
        
        S //= k

        dp = [-1] * (1 << (N + 1))
        def dfs(status, edge, sum):
            if edge == 0:
                return status == 0

            if dp[status] != -1: return dp[status]

            ans = 0
            for i in range(N):
                if (status & (1 << i)) == 0: continue
                if sum - nums[i] < 0: continue

                if sum == nums[i]:
                    ans = dfs(status ^ (1 << i), edge - 1, S)
                else:
                    ans = dfs(status ^ (1 << i), edge, sum - nums[i])

                if ans == 1: break
            
            dp[status] = ans
            return ans

        return dfs((1 << N) - 1, k, S) 

37029