<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:
        
        if sum(nums) % k != 0:
            return False

        target = sum(nums) / k
        cache = {}
        def dfs(candidate, CurSum, k):
            if (candidate, CurSum) in cache:
                return cache[(candidate, CurSum)]

            if CurSum > target:
                return False

            if k == 0:
                return True

            if CurSum == target: 
                if dfs(candidate, 0, k-1):
                    return True

            for i in range(len(candidate)):
                remain_candidate = candidate[:i] + candidate[i+1:]
                if dfs(tuple(remain_candidate), CurSum + candidate[i], k):
                    cache[(candidate, CurSum)] = True
                    return True

            cache[(candidate, CurSum)] = False
            return False

        return dfs(tuple(nums), 0, k)





















        # Hard
        # https://www.youtube.com/watch?v=mBk4I0X46oI
        # Normal backtrack is O(k^N) Why????
        # We need to make it O(2^(k*n)) since 2 is usually smaller than k
        # Stack k "binary" subtree, after each subtree, we need to exclude numbers that are used

        target = sum(nums) / k # Sum of each subset
        if sum(nums) % k != 0:
            return False

        nums.sort(reverse = True) # Speed up
        used = [False] * len(nums)
        def backtrack(i, k, CurSum):
            print(i, k, CurSum)
            if k == 0:
                return True
            
            if CurSum == target:
                return backtrack(0, k-1, 0)

            for j in range(i, len(nums)):
                # Since we already sorted the array, the duplicated numbers are also stuck together. 
                # We can tweak the for loop a little bit to avoid duplicated backtracking (2nd condition)
                if used[j] or CurSum + nums[j] > target or (j > 0 and nums[j] == nums[j-1] and not used[j-1]):
                    continue
                
                used[j] = True
                if backtrack(j+1, k, CurSum + nums[j]):
                    #print('aaa')
                    return True

                # If above doesn't succeed, reset the value back to False since we don't use it
                used[j] = False
            
            return False

        return backtrack(0, k, 0)
31595