<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 k > len(nums):
            return False
        sum_ = sum(nums)
        if sum_ % k != 0:
            # 不能整除，提前退出
            return False
        # 使用位图技巧
        used = [0]*len(nums)
        target = sum_ // k
        # k 号桶初始什么都没装，从 nums[0] 开始做选择
        nums.sort()
        memo = {}
        return self.backtrack(k, 0, nums, 0, used, memo, target)


    def backtrack(self, k: int, bucket: int, nums: List[int], 
                  start: int, used: List[int], memo: Dict, target: int) -> bool:
        if k == 0:
            return True
        state = str(used)
        if bucket == target:
            # 装满了当前桶，递归穷举下一个桶的选择
            res = self.backtrack(k - 1, 0, nums, 0, used, memo, target)
            # 缓存结果
            memo[state] = res
            return res
        if state in memo:
            # 避免冗余计算
            return memo[state]
        for i in range(start, len(nums)):
            if used[i]:
                # nums[i] 已经被装入别的桶中
                continue
            if nums[i] + bucket > target:
                # 装不下，剪枝
                continue
            # 做选择
            used[i] = 1
            # 递归穷举下一个数字是否装入当前桶
            if self.backtrack(k, bucket + nums[i], nums, i + 1, used, memo, target):
                return True
            # 撤销选择
            used[i] = 0
        return False
17105