# 698. Partition to K Equal Sum Subsets

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/partition-to-k-equal-sum-subsets/description/

> 内容描述

```
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal.

Example 1:
Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
Note:

1 <= k <= len(nums) <= 16.
0 < nums[i] < 10000.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N!)******- 空间复杂度: O(N)******



将问题一步一步缩小到找一个subset的sum为target的问题，即剩下的整个数组的sum是否为target
```python
class Solution(object):
    def canPartitionKSubsets(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        def dfs(nums, target, num, k):
            if k == 0:
                return True
            for i in range(len(nums)):
                new_nums = nums[:i] + nums[i+1:]
                if num + nums[i] == target:
                    if dfs(new_nums, target, 0, k-1):
                        return True
                elif num + nums[i] < target:
                    if dfs(new_nums, target, num+nums[i], k):
                        return True
                elif num == 0: # 有一个数比target还大，直接返回False
                    return False
            return False
        if sum(nums) % k != 0:
            return False
        target = sum(nums) / k
        nums.sort(reverse = True) # 逆序排序，先从大的开始判断，速度会更快
        return dfs(nums, target, 0, k)
```
